用 pandas 中的 empty_rows 替换 pandas 数据框中的 NaN [重复]

Posted

技术标签:

【中文标题】用 pandas 中的 empty_rows 替换 pandas 数据框中的 NaN [重复]【英文标题】:Replace the NaNs in pandas dataframe with empty_rows in pandas [duplicate] 【发布时间】: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().

我该如何解决这个问题?

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于用 pandas 中的 empty_rows 替换 pandas 数据框中的 NaN [重复]的主要内容,如果未能解决你的问题,请参考以下文章