我试图根据另一个 DataFrame 的列选择 DataFrame 的子集。
数据框看起来像这样:
a b c d
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
a b
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
我想获取第一个数据帧的所有行,以获取两个数据帧中包含的列。我的结果应该是这样的:
a b
0 0 1
1 4 5
2 8 9
3 12 13
您可以使用pd.Index.intersection https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html或其语法糖&
:
intersection_cols = df1.columns & df2.columns
res = df1[intersection_cols]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)