python-3.x - 将列 wrt 中的 NULL 或 NA 替换为 pandas 数据框中的其他列
问题描述
我有一张桌子:
df = pd.DataFrame([[0.1, 2, 55, 0,np.nan],
[0.2, 4, np.nan, 1,99],
[0.6, np.nan, 22, 5,88],
[1.4, np.nan, np.nan, 4,77]],
columns=list('ABCDE'))
A B C D E
0 0.1 2.0 55.0 0 NaN
1 0.2 NaN NaN 1 99.0
2 0.6 NaN 22.0 5 88.0
3 1.4 NaN NaN 4 77.0
我想根据 A 列的条件替换 B 列中的 NaN 值。示例:
When B is NULL and value in `column A > 0.2 and < 0.6` replace "NaN" in column B as 5
When B is NULL value in `column A > 0.6 and < 2` replace "NaN" in column B as 10
我试过这样的事情:
if df["A"]>=val1 and pd.isnull(df['B']):
df["B"]=5
elif df["A"]>=val2 and df["A"]<val3 and pd.isnull(df['B']):
df["B"]=10
elif df["A"]<val4 and pd.isnull(df['B']):
df["B"]=15
上面的代码不起作用。
请让我知道是否有任何其他替代方法使用 for 循环或应用函数来迭代 pandas 数据帧。
解决方案
您可以使用掩码:
df['B'] = df['B'].mask((df['A']>0.2) & (df['A']<0.6), df['B'].fillna(5))
df['B'] = df['B'].mask((df['A']>0.6) & (df['A']<2), df['B'].fillna(10))
或者您可以尝试 np.where 但我猜它会涉及很长的条件。
推荐阅读
- javascript - 饼图未在扩展面板上呈现(EXT JS)
- python - 将 Ajax 添加到 Django
- api - 嘿,有人可以给我看一些关于 discord.py API 的代码吗?使用来自网站的 api
- python - 为开发设置沙盒容器环境的好方法是什么?
- python - 解包字典
- python - 如何从 sqlalchemy .execute() 方法中获取价值?Python + Sqlalchemy + MS SQL 服务器
- acumatica - 报表设计器中 Acumatica 中金额字段的文字表示
- python - 如何解决爬取GitHub问题正文时出现非法字符的问题?
- yocto - yocto如何支持ftp命令?
- python - 未找到 Anaconda3 Python shapely 模块