首页 > 解决方案 > Python Dataframe 包括列表中的公共点

问题描述

我有一个由列表组成的数据框。两列:x 和 y。我想包括 x 中的共同点和 y 中的对应点。

我的代码:

df = 
                  x                        y     
0     [0, 1.1, 2, 8, 10]  [0, 1.5, 2.5, 3.5, 4.5]  
1     [0, 1.1, 3, 4, 10]  [0, 100, 200, 300, 400]  
2     [0, 1.1, 4, 9, 10]  [0, 300, 500, 700, 900] 

预期答案:

df = 
          xcmd            y     
0     [0, 1.1, 10]  [0, 1.5, 4.5]  
1     [0, 1.1, 10]  [0, 100, 400]  
2     [0, 1.1, 10]  [0, 300, 900]  

标签: pythonpandasdataframenumpy

解决方案


这是我的建议:

from collections import Counter

temp= df.apply(pd.Series.explode)

l=Counter(temp.x)

s=[x for x, count in l.items() if count==df.shape[0]]

res = temp[temp.x.isin(s)]

res = res.groupby(level=0).agg(list)

>>>print(res)   
              x              y
0  [0, 1.1, 10]  [0, 1.5, 4.5]
1  [0, 1.1, 10]  [0, 100, 400]
2  [0, 1.1, 10]  [0, 300, 900]

如果您需要一些关于它如何工作的解释,请告诉我。


推荐阅读