python - 在 pandas DataFrame 中搜索列

标签 python pandas numpy dataframe

我需要获取 pandas DataFrame 的列名,其中的列与 numpy 数组中的列匹配。

示例

import numpy as np
import pandas as pd

x = pd.DataFrame( data=[[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]], columns=list('abc') )

y = np.array( x[['b','c']] )
y

y 然后有来自 DataFrame 的第二列和第三列:

array([[0, 1],
       [1, 0],
       [0, 0],
       [1, 1],
       [1, 0],
       [1, 1]])

如何获取 xy 的列名?(在本例中为 bc)

我正在寻找类似的东西:

x[ x==y ].columns

pd.DataFrame(y).isin(x)

该示例的动机是特征选择问题,取自 the sklearn page .


我正在使用 numpy 1.11.1 和 pandas 0.18.1。

最佳答案

这是 NumPy broadcasting 的一种方法-

x.columns[(x.values[...,None] == y[:,None]).all(0).any(1)]

关于python - 在 pandas DataFrame 中搜索列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40596306/

相关文章:

python - 从 pandas 中绘制时间线中的时间段

python - sklearn 中 score 和 accuracy_score 的区别

python - Python SSH:使用fabric.api替代paramiko

pandas - 使用多索引创建空的 pandas 数据框

python - 在 python 中使用 numpy 对 100x100 数组进行排序

python - 如何在列表的间隔之间填充元素

python - PyQt4 : Window shows up at another position after hide() and show()

pandas - Pandas DataFrame如何查询最近的日期时间索引?

python - 在 Pandas 中切片时出现值错误

python - np.argsort 如何在 pandas DataFrame 中工作?