【问题标题】:Replace the NaNs in pandas dataframe with empty_rows in pandas [duplicate]用 pandas 中的 empty_rows 替换 pandas 数据框中的 NaN [重复]
【发布时间】:2021-11-20 13:22:40
【问题描述】:

我有下表(df):

Col1 Col2 Col3
A1 finished 1234
A2 ongoing 1235
A3 NaN 1236
A4 finished 1237
A5 started 1238
A6 NaN 1239

我想用 empty_row 替换数据框中的 NaN。我该怎么做?

期望的输出:

Col1 Col2 Col3
A1 finished 1234
A2 ongoing 1235
A3 empty_row 1236
A4 finished 1237
A5 started 1238
A6 empty_row 1239

到目前为止我尝试了什么?

if df['col2'] == 'NaN':
   df['col2'] = 'empty_row'

我收到以下错误:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我该如何解决这个问题?

【问题讨论】:

    标签: python pandas dataframe replace nan


    【解决方案1】:

    你应该使用fillna方法https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html

    df['col2'] = df['col2'].fillna('empty_row')
    

    【讨论】:

      猜你喜欢
      • 2022-10-05
      • 2018-11-08
      • 2016-10-16
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      相关资源
      最近更新 更多