首先回填缺失值 by bfill
,然后选择第一列并删除第二级MultiIndex
by DataFrame.droplevel
:
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