【问题标题】:Merge dataframe rows when values are NaN [duplicate]当值为 NaN 时合并数据框行 [重复]
【发布时间】:2020-01-01 06:39:14
【问题描述】:

我想像下面的示例那样展平数据框。

我有下一个数据框:

    file name   format  location
0   movie1.mp4  NaN     NaN
1   NaN         NaN     D:/mymovies
2   NaN         mp4     NaN

我想把它转换成:

    file name   format  location
0   movie1.mp4  mp4 D:/mymovies

有什么想法吗?谢谢!

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    我相信您可以对第一列使用前向填充,如果第一个非缺失值是组的第一个值,然后与 GroupBy.first 聚合以获得每个组的第一个非缺失值:

    df = df.groupby(df['file name'].ffill()).first().reset_index(drop=True)
    print (df)
        file name format     location
    0  movie1.mp4    mp4  D:/mymovies
    

    详情

    print (df['file name'].ffill())
    0    movie1.mp4
    1    movie1.mp4
    2    movie1.mp4
    Name: file name, dtype: object
    

    如果第一列是索引:

    df = df.groupby(df.index.to_series().ffill()).first().reset_index()
    print (df)
        file name format     location
    0  movie1.mp4    mp4  D:/mymovies
    

    【讨论】:

    猜你喜欢
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2012-02-08
    • 2012-05-30
    相关资源
    最近更新 更多