python - 用 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().
我该如何解决这个问题?
解决方案
您应该使用fillna
方法https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html
df['col2'] = df['col2'].fillna('empty_row')
推荐阅读
- java - 在服务器上部署多模块项目后,maven 是否需要互联网连接
- batch-file - 如何使用批处理文件运行 Teraterm 和 TTL 文件?
- javascript - 移动设备与 css 的触摸事件
- css - 将文本复制到离子中的剪贴板
- javascript - 使用 HTML 和 Javascript 将字符串格式的日期与日期格式的当前日期进行比较
- mysql - mysql用另一个字符替换一个字符
- d3.js - c3js多色设计
- internet-explorer - Robot 框架是否与 Windows 10 操作系统兼容(IE 版本 -> 11.665.16299.0)
- c# - 如何在 Xamarin 表单(如 android)中拥有类似于 colors.xml 的文件
- java - @RecentlyNonNull 注释是什么?