我正在尝试根据另一个 DataFrame 的列选择一个 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
我想获取第一个 Dataframe 中包含在两个 DataFrame 中的列的所有行。我的结果应该是这样的:
a b
0 0 1
1 4 5
2 8 9
3 12 13
最佳答案
您可以使用 pd.Index.intersection
或其语法糖&
:
intersection_cols = df1.columns & df2.columns
res = df1[intersection_cols]
关于python - 根据另一个 DataFrame 选择一个 DataFrame 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52163161/