在Pandas DataFrame中为两列应用特定函数

问题描述 投票:0回答:2

我有一个Pandas DataFrame有两列,每行包含一个元素列表。我正在尝试使用pandas.apply方法为每行找到两列之间的集合差异。

我的df例如

           A              B
0     ['a','b','c']     ['a']
1     ['e', 'f', 'g']   ['f', 'g']

所以看起来应该是这样的:

df.apply(set_diff_func, axis=1)

我想要实现的目标:

0      ['b','c']
1      ['e']

我可以使用iterrows制作它,但我曾经读过,在可能的情况下使用apply会更好。

python pandas
2个回答
3
投票

怎么样

df.apply(lambda row: list(set(row['A']) - set(row['B'])), axis = 1)

要么

(df['A'].apply(set) - df['B'].apply(set)).apply(list)

1
投票

这是您需要的功能,您可以通过将col1col2参数传递给args中的apply选项来更改列的名称:

def set_diff_func(row, col1, col2):
    return list(set(row[col1]).difference(set(row[col2])))

这应该返回所需的结果:

>>> dataset = pd.DataFrame(
    [{'A':['a','b','c'], 'B':['a']},
     {'A':['e', 'f', 'g'] , 'B':['f', 'g']}])
>>> dataset.apply(set_diff_func, axis=1, args=['A','B'])
0    [c, b]
1       [e]
© www.soinside.com 2019 - 2024. All rights reserved.