在Pandas DataFrame中跨多个列的映射方法 [英] Mapping methods across multiple columns in a Pandas DataFrame
问题描述
我有一个Pandas数据框,其中的值是列表:
I have a Pandas dataframe where the values are lists:
import pandas as pd
DF = pd.DataFrame({'X':[[1, 5], [1, 2]], 'Y':[[1, 2, 5], [1, 3, 5]]})
DF
X Y
0 [1, 5] [1, 2, 5]
1 [1, 2] [1, 3, 5]
我想检查X中的列表是否是Y中列表的子集.对于单个列表,我们可以使用set(x).issubset(set(y))
进行.但是,我们如何在Pandas数据列中做到这一点?
I want to check if the lists in X are subsets of the lists in Y. With individual lists, we can do this using set(x).issubset(set(y))
. But how would we do this across Pandas data columns?
到目前为止,我唯一想到的就是使用单个列表作为解决方法,然后将结果转换回Pandas.这个任务似乎有点复杂:
So far, the only thing I've come up with is to use the individual lists as a workaround, then convert the result back to Pandas. Seems a bit complicated for this task:
foo = [set(DF['X'][i]).issubset(set(DF['Y'][i])) for i in range(len(DF['X']))]
foo = pd.DataFrame(foo)
foo.columns = ['x_sub_y']
pd.merge(DF, foo, how = 'inner', left_index = True, right_index = True)
X Y x_sub_y
0 [1, 5] [1, 2, 5] True
1 [1, 2] [1, 3, 5] False
有没有更简单的方法来实现这一目标?可能使用.map
或.apply
吗?
Is there a easier way to achieve this? Possibly using .map
or .apply
?
推荐答案
使用set
和issubset
:
DF.assign(x_sub_y = DF.apply(lambda x: set(x.X).issubset(set(x.Y)), axis=1))
输出:
X Y x_sub_y
0 [1, 5] [1, 2, 5] True
1 [1, 2] [1, 3, 5] False
这篇关于在Pandas DataFrame中跨多个列的映射方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!