python-3.x - 如果另一个列值在列表或集合中,则使用二进制值填充 pandas 数据框中的新列
问题描述
我有一个熊猫数据框,我想根据第一列中的条目是否在列表中来创建一个新列,其值为“列表中”或“不在列表中”。为了说明,我在下面有一个玩具示例。我有一个可行的解决方案,但是它看起来很麻烦而且不是很pythonic。我也得到一个SettingWithCopyWarning
. 在 python 中是否有更好或更推荐的方法来实现这一点?
#creating a toy dataframe with one column
df = pd.DataFrame({'col_1': [1,2,3,4,6]})
#the list we want to check if any value in col_1 is in
list_ = [2,3,3,3]
#creating a new empty column
df['col_2'] = None
col_1 col_2
0 1 None
1 2 None
2 3 None
3 4 None
4 6 None
我的解决方案是遍历第一列并填充第二列
for index, i in enumerate(df['col_1']):
if i in list_:
df['col_2'].iloc[index] = 'in list'
else:
df['col_2'].iloc[index] = 'not in list'
col_1 col_2
0 1 not in list
1 2 in list
2 3 in list
3 4 not in list
4 6 not in list
这会产生正确的结果,但我想学习一种更 Pythonic 的方式来实现这一点。
解决方案
Series.isin
与 一起使用Series.map
:
In [1197]: df['col_2'] = df.col_1.isin(list_).map({False: 'not in list', True: 'in list'})
In [1198]: df
Out[1198]:
col_1 col_2
0 1 not in list
1 2 in list
2 3 in list
3 4 not in list
4 6 not in list
推荐阅读
- python - SELENIUM Python - 尝试访问某些数据进行处理
- tsql - SQL:使用电子表格中的数据更新多行
- javascript - 带有 Wild Web Dev 的 Eclipse 2020 - Javascript 颜色问题
- go - 如何在go中处理异步go函数值
- javascript - 使函数返回子函数,但默认为另一个函数(Node.js/JS)
- java - 使用十进制格式 Android JAVA 格式化 ValueAmimator setText
- node.js - React npm start not working at it 重新安装时失败
- c++ - 将枚举重构为枚举类阴影命名空间
- python - 字段 'id' 需要一个数字,但得到了 'favicon.ico'
- javascript - 在 Reactstrap 不受控制的轮播组件中自定义图像样式