首页 > 解决方案 > 用 pandas 中的 empty_rows 替换 pandas 数据框中的 NaN

问题描述

我有下表(df):

Col1 Col2 Col3
A1 完成的 1234
A2 进行中 1235
A3 1236
A4 完成的 1237
A5 开始 1238
A6 1239

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

期望的输出:

Col1 Col2 Col3
A1 完成的 1234
A2 进行中 1235
A3 空行 1236
A4 完成的 1237
A5 开始 1238
A6 空行 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().

我该如何解决这个问题?

标签: pythonpandasdataframereplacenan

解决方案


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

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

推荐阅读