【问题标题】:Python: Fill empty rows of Dataframe with unique column value [duplicate]Python:用唯一的列值填充Dataframe的空行[重复]
【发布时间】:2022-02-18 16:55:30
【问题描述】:

得到数据框df

State   Item        Space   Date
AAA     Grape       0.125   2022-02-11
        Beans       0.0
AAA     Mango       0.25    2022-02-11
AAA     Beetroot    0.375   2022-02-11
        Carrot      0.5

需要用该列的唯一值填充行中的空值。 试过df['State'].fillna(df['State'].unique(), inplace=True),没用。

预期输出:

State   Item        Space   Date
AAA     Grape       0.125   2022-02-11
AAA     Beans       0.0     2022-02-11
AAA     Mango       0.25    2022-02-11
AAA     Beetroot    0.375   2022-02-11
AAA     Carrot      0.5     2022-02-11

【问题讨论】:

  • 您需要第一列和最后一列的常量值吗?还是有一些群?

标签: python-3.x pandas dataframe unique fillna


【解决方案1】:

如果想用第一个非缺失值替换每一列,首先将空字符串替换为缺失值,然后转发和回填缺失值:

df = df.replace('', np.nan)

df = df.ffill().bfill()

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 2021-08-02
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    相关资源
    最近更新 更多