合并连续列中相同变量的级别

2024-04-26 17:41:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv数据文件,其中有两个标题,这意味着一个标题作为一个问题和第二个作为一个子标题,其中有多个层次或答案的主要标题。当前csv如下表所示

Header  Which country do you live?        Which country you previously visited? 
Users    Canada  USA   UK  Mexico  Norway India  Singapore  Pakistan 
User 1   Canada                                  Singapore
User 2                 UK                 India              
User 3                     Mexico                           Pakistan
User 4                             Norway India 

我需要把它转换成下表

Users   Which country do you live?  Which country you previously visited?
User 1  Canada                      Singapore
User 2  UK                          India
User 3  Norway                      Pakistan
User 4  Mexico                      India

有人能帮我吗?你知道吗

我的数据就是这样的 enter image description here

我的输入文件是这样的 enter image description here 这就是我最终输出的样子 enter image description here


Tags: csvyoulive标题whichdocountryuk
1条回答
网友
1楼 · 发布于 2024-04-26 17:41:37

首先用bfill填充缺少的值,然后选择第一列并用^{}删除第二级MultiIndex

print (df.columns)
MultiIndex(levels=[['Header', 'Which country do you live?'],
                   ['Canada', 'Mexico', 'UK', 'USA', 'Users']],
           codes=[[0, 1, 1, 1, 1], [4, 0, 3, 2, 1]])

#if first column is not index, create it
#df = df.set_index([df.columns[0]])
#if empty strings repalce them to NaNs
#df = df.replace('', np.nan)

df = df.bfill(axis=1).iloc[:, 0].reset_index().droplevel(level=1, axis=1)
print (df)
   Header Which country do you live?
0  User 1                     Canada
1  User 2                         UK
2  User 3                     Mexico
3  User 4                     Norway

编辑:

df = df.groupby(level=0, axis=1).apply(lambda x: x.bfill(axis=1).iloc[:, 0])
print (df)
   Header Which country do you live? Which country you previously visited?
0  User 1                     Canada                             Singapore
1  User 2                         UK                                 India
2  User 3                     Mexico                              Pakistan
3  User 4                     Norway                                 India

相关问题 更多 >