首页 > 解决方案 > 如果另一个列值在列表或集合中,则使用二进制值填充 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 的方式来实现这一点。

标签: python-3.xpandas

解决方案


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

推荐阅读