【问题标题】:Merge multiple rows into 1 row将多行合并为 1 行
【发布时间】:2017-06-21 16:23:47
【问题描述】:

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(),但这不起作用。

【问题讨论】:

  • 我认为 DF.dropnan() 会做到的
  • @SaulloCastro 你的意思是df.dropna()?它没有。

标签: python python-2.7 pandas numpy


【解决方案1】:

你可以使用:

#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

【讨论】:

    猜你喜欢
    • 2018-01-11
    • 2022-01-13
    • 1970-01-01
    • 2021-10-24
    • 2023-03-05
    • 2021-10-06
    • 2012-06-26
    • 2012-06-20
    相关资源
    最近更新 更多