在R中,当您需要根据列名检索列索引时,您可以这样做
idx <- which(names(my_data)==my_colum_name)
有没有办法对熊猫数据框架做同样的事情?
在R中,当您需要根据列名检索列索引时,您可以这样做
idx <- which(names(my_data)==my_colum_name)
有没有办法对熊猫数据框架做同样的事情?
当前回答
这里有一个通过列表理解的解决方案。Cols是要获取索引的列的列表:
[df.columns.get_loc(c) for c in cols if c in df]
其他回答
更新:" 0.25.0版后已移除:使用np.asarray(..)或DataFrame.values()代替。
如果你想从列位置获取列名(与OP问题相反),你可以使用:
>>> df.columns.values()[location]
使用@DSM示例:
>>> df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
>>> df.columns
Index(['apple', 'orange', 'pear'], dtype='object')
>>> df.columns.values()[1]
'orange'
其他方式:
df.iloc[:,1].name
df.columns[location] #(thanks to @roobie-nuby for pointing that out in comments.)
这里有一个通过列表理解的解决方案。Cols是要获取索引的列的列表:
[df.columns.get_loc(c) for c in cols if c in df]
当列可能存在,也可能不存在时,下面的(来自上面的变体)可以工作。
ix = 'none'
try:
ix = list(df.columns).index('Col_X')
except ValueError as e:
ix = None
pass
if ix is None:
# do something
当您希望找到多个列匹配时,可以使用使用searchsorted方法的向量化解决方案。因此,df作为数据帧,query_cols作为要搜索的列名,实现将是-
def column_index(df, query_cols):
cols = df.columns.values
sidx = np.argsort(cols)
return sidx[np.searchsorted(cols,query_cols,sorter=sidx)]
试运行-
In [162]: df
Out[162]:
apple banana pear orange peach
0 8 3 4 4 2
1 4 4 3 0 1
2 1 2 6 8 1
In [163]: column_index(df, ['peach', 'banana', 'apple'])
Out[163]: array([4, 1, 0])
DSM的解决方案是有效的,但是如果你想要一个直接等价的方法(df。Columns == name).nonzero()