python - pandas.DataFrame.apply() 使用方括号过滤时产生 NaN
问题描述
import pandas as pd
df = pd.DataFrame({"First_Column": [-2,-1,1,2,3]})
df['Second_Column']='Good'
df.loc[:, 'Second_Column']=df[df.First_Column>0]['Second_Column'].apply(lambda x: 'Bad')
当我运行它时,我得到Bad
and NaN
,Second_Column
而不是Good
and Bad
。为什么apply()
用 覆盖不符合条件的值NaN
?
解决方案
通过使用mask
df.Second_Column=df.Second_Column.mask(df.First_Column>0,'Bad')
df
Out[441]:
First_Column Second_Column
0 -2 Good
1 -1 Good
2 1 Bad
3 2 Bad
4 3 Bad
或者
df.loc[df.First_Column>0,'Second_Column']='Bad'
df
Out[443]:
First_Column Second_Column
0 -2 Good
1 -1 Good
2 1 Bad
3 2 Bad
4 3 Bad
或者使用np.where
更直接的
df['Second_Column']=np.where(df.First_Column>0,'Bad','Good')
df
Out[445]:
First_Column Second_Column
0 -2 Good
1 -1 Good
2 1 Bad
3 2 Bad
4 3 Bad
推荐阅读
- mongodb - MongoDB 与架构布局的混淆
- git - Using GIT Api can I find the branch name from a commit id
- javascript - 在javascript中的两个子字符串之间提取数据
- javascript - Promise.all 并发或并行运行
- javascript - 单击按钮,然后使用 Google Apps 脚本进行抓取
- typescript - 为什么 Typescript 项目引用使用父 tsconfig 文件而不是引用自己的 tsconfig 文件?
- websocket - 如何无法在 websockets 中检测到客户端断开连接
- python - 是否可以恢复 pipenv 虚拟环境
- java - 我如何使用 OpenImaj 只听屏幕的两个特定区域
- java - 将char放入int数组是什么意思,是ASC号吗?