python - 根据另一个 DataFrame 选择一个 DataFrame 的列

标签 python pandas dataframe indexing intersection

我正在尝试根据另一个 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/

相关文章:

python - 是否有与 __import__ 等效的 __reload__ 函数?

python - 在 Python 中打开一个 .txt 文件

Python 'String reversing' 程序

python - 没有匹配时打印空数据框

python - 带有日期时间索引的 Pandas Pivot

python - 使用 ~isin([list_of_substrings]) 过滤 Dataframe

python - 在 python 中计算 numpy 的欧氏距离

Python。 Pandas 。 CSV。计算其他列值的平均值

python - 查找所有列中包含 NaN 的 pandas Groupby

python - 我如何删除 Pandas 中的过滤器数据(数据处理)