python - 带有 isin 的 Pandas 函数

标签 python pandas

我有一个这样的数据框:

aa        bb  cc
[a, x, y] a   1
[b, d, z] b   2
[c, e, f] s   3
np.nan    d   4

我正在尝试像这样创建一个新列:

aa        bb  cc dd
[a, x, y] a   1  True
[b, d, z] b   2  True
[c, e, f] s   3  False
np.nan    d   4  False

我目前的解决方案是:

def some_function(row):
    if row['bb].isin(row['aa'])==True:
        return True
    return False
df['dd'] = df.apply(lambda row: some_function(row), axis=1)

但这会抛出错误 ("'str' object has no attribute 'isin'", 'occurred at index 0')

我怀疑,因为在检查 isin 时我遗漏了一些东西。

基本上,我需要检查 bb 的 str 值是否在列 aa 中,每个单元格中都有一个列表。

关于如何做到这一点有什么想法吗?

最佳答案

您需要参数 in 来检查列表中的成员资格:

df['dd'] = df.apply(lambda x: x.bb in x.aa, axis=1)
print (df)
          aa bb  cc     dd
0  [a, x, y]  a   1   True
1  [b, d, z]  b   2   True
2  [c, e, f]  s   3  False

编辑:

df['dd'] = df.apply(lambda x: (x.bb in x.aa) and (x.cc == 1), axis=1) 
print (df)
          aa bb  cc     dd
0  [a, x, y]  a   1   True
1  [b, d, z]  b   2  False
2  [c, e, f]  s   3  False

或者:

df['dd'] = df.apply(lambda x: x.bb in x.aa, axis=1) & (df['cc'] == 1)
print (df)
          aa bb  cc     dd
0  [a, x, y]  a   1   True
1  [b, d, z]  b   2  False
2  [c, e, f]  s   3  False

编辑:

df['dd'] = df.apply(lambda x: x.bb in x.aa if type(x.aa) == list else False, axis=1) 
print (df)
          aa bb  cc     dd
0  [a, x, y]  a   1   True
1  [b, d, z]  b   2   True
2  [c, e, f]  s   3  False
4        NaN  d   4  False

关于python - 带有 isin 的 Pandas 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46806827/

相关文章:

python - pyqt4程序,如何制作win安装程序

python - 为什么我的 implemented_function() 导致 NameError : global name 'Derivative' is not defined?

python - Pandas::将一列的值作为列

python - Django:如何引发 Http401 和 Http403 异常,如 Http404,RAISE EXCEPTION not RESPONSE

python - 使用另一个数据帧中的值创建新的 dask 数据帧列会导致 "chunk sizes are unknown"错误

python - Pandas:欧式date_range

python - 如何将列数据类型从 'string ' 转换为 'boolean' 并保留 NaN?

python - Pandas 矢量化: Compute the fraction of each group that meets a condition

python - 拆分单元格中具有多个值的行并将其追加回数据列表

Python:找不到文件(pySerial)