python - 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]
解决方案
这是我的建议:
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]
如果您需要一些关于它如何工作的解释,请告诉我。
推荐阅读
- java - 如何在 Hibernate 5 的 @ManyToMany 关系中添加额外的列
- python - 无法在循环内使用条件(使用 describe_instances)
- git - 为什么我们需要 git 合并?
- java - 如何在 Android Q 中将文件从资产移动到内部存储
- c# - 从 C# 中的 Azure 函数流式传输视频
- visual-studio - 为不同文件夹中的源创建静态库 .lib
- android - 在颤动中,底部超载了 248 像素
- wordpress - 标题联系信息是否编码到我的 wordpress 网站的 css 文件中?
- python - Python Folium Choropleth Map - 图例分位数重叠
- python - python 临时变量随实际变量变化;蛇游戏pygame