pd.read_csv()
的数据:
Name Job Place Age
John None None None
None Doctor None None
None None UK None
None None None 50
Alex None None None
None Engr None None
None None US None
None None None 45
单行的信息包含在对角线上。有没有办法将对角线转换并折叠成行?生成的数据框将有 2 行。
尝试使用 df.ffill()
/df.bfill()
和 df.drop_duplicates()
但这行不通。
最佳答案
您可以使用:
#change string None to NaN
df = df.replace({'None':np.nan})
#multiindex
df.index = [df.index, df.Name.notnull().cumsum() - 1]
#remove nan by stack
df = df.stack().reset_index(name='val')
#pivoting
df = df.pivot(index='Name', columns='level_2', values='val')
print (df)
level_2 Age Job Name Place
Name
0 50 Doctor John UK
1 45 Engr Alex US
关于python - 将多行合并为 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42038788/