2 回答

TA贡献1836条经验 获得超3个赞
方法1
这是一种利用向量化的方法NumPy broadcasting-
df.columns[(df.values == np.asarray(x)[:,None]).all(0)]
样品运行-
In [367]: df
Out[367]:
0 1 2 3 4 5 6 7 8 9
0 7 1 2 6 2 1 7 2 0 6
1 5 4 3 3 2 1 1 1 5 5
2 7 7 2 2 5 4 6 6 5 7
3 0 5 4 1 5 7 8 2 2 4
4 7 1 0 4 5 4 3 2 8 6
In [368]: x = df.iloc[:,2].values.tolist()
In [369]: x
Out[369]: [2, 3, 2, 4, 0]
In [370]: df.columns[(df.values == np.asarray(x)[:,None]).all(0)]
Out[370]: Int64Index([2], dtype='int64')
方法#2
另外,这是另一个使用views-
def view1D(a, b): # a, b are arrays
a = np.ascontiguousarray(a)
b = np.ascontiguousarray(b)
void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
return a.view(void_dt).ravel(), b.view(void_dt).ravel()
df1D_arr, x1D = view1D(df.values.T,np.asarray(x)[None])
out = np.flatnonzero(df1D_arr==x1D)
样品运行-
In [442]: df
Out[442]:
0 1 2 3 4 5 6 7 8 9
0 7 1 2 6 2 1 7 2 0 6
1 5 4 3 3 2 1 1 1 5 5
2 7 7 2 2 5 4 6 6 5 7
3 0 5 4 1 5 7 8 2 2 4
4 7 1 0 4 5 4 3 2 8 6
In [443]: x = df.iloc[:,5].values.tolist()
In [444]: df1D_arr, x1D = view1D(df.values.T,np.asarray(x)[None])
In [445]: np.flatnonzero(df1D_arr==x1D)
Out[445]: array([5])

TA贡献1895条经验 获得超7个赞
尝试这个:
In [91]: x = np.array(x)
In [94]: df.apply(lambda col: col.eq(x).all())
Out[94]:
m1lenhr False
m1lenmin True
m1citywt False
m1a12a False
cm1age False
cm1numb False
m1b1a False
m1b1b False
m1b12a False
m1b12b False
dtype: bool
In [95]: df.columns[df.apply(lambda col: col.eq(x).all()).values]
Out[95]: Index(['m1lenmin'], dtype='object')
添加回答
举报