您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 在pandas中查找与数组匹配的列名

5b51 2022/1/14 8:21:46 python 字数 3866 阅读 543 来源 www.jb51.cc/python

我有一个大型数据帧(5000 x 12039),我想获得与numpy数组匹配的列名.例如,如果我有桌子 m1lenhr m1lenmin m1citywt m1a12a cm1age cm1numb m1b1a m1b1b m1b12a m1b12b ... kind_attention_scale_10 kind_

概述

我有一个大型数据帧(5000 x 12039),我想获得与numpy数组匹配的列名.

例如,如果我有桌子

        m1lenhr m1lenmin    m1citywt    m1a12a  cm1age  cm1numb m1b1a   m1b1b   m1b12a  m1b12b  ... kind_attention_scale_10 kind_attention_scale_22 kind_attention_scale_21 kind_attention_scale_15 kind_attention_scale_18 kind_attention_scale_19 kind_attention_scale_25 kind_attention_scale_24 kind_attention_scale_27 kind_attention_scale_23
challengeID                                                                                 
1   0.130765    40.0    202.485367  1.893256    27.0    1.0 2.0 0.0 2.254198    2.289966    ... 0   0   0   0   0   0   0   0   0   0
2   0.000000    40.0    45.608219   1.000000    24.0    1.0 2.0 0.0 2.000000    3.000000    ... 0   0   0   0   0   0   0   0   0   0
3   0.000000    35.0    39.060299   2.000000    23.0    1.0 2.0 0.0 2.254198    2.289966    ... 0   0   0   0   0   0   0   0   0   0
4   0.000000    30.0    22.304855   1.893256    22.0    1.0 3.0 0.0 2.000000    3.000000    ... 0   0   0   0   0   0   0   0   0   0
5   0.000000    25.0    35.518272   1.893256    19.0    1.0 1.0 6.0 1.000000    3.000000    ... 0

我想做这个:

x = [40.0,40.0,35.0,30.0,25.0]
find_column(x)

并让find_column(x)返回m1lenmin

这是一个利用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

或者,这是另一个使用观点的概念 –

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,np.asarray(x)[None])

In [445]: np.flatnonzero(df1D_arr==x1D)
Out[445]: array([5])

总结

以上是编程之家为你收集整理的python – 在pandas中查找与数组匹配的列名全部内容,希望文章能够帮你解决python – 在pandas中查找与数组匹配的列名所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶