在R中,当您需要根据列名检索列索引时,您可以这样做
idx <- which(names(my_data)==my_colum_name)
有没有办法对熊猫数据框架做同样的事情?
在R中,当您需要根据列名检索列索引时,您可以这样做
idx <- which(names(my_data)==my_colum_name)
有没有办法对熊猫数据框架做同样的事情?
当前回答
import random
def char_range(c1, c2): # question 7001144
for c in range(ord(c1), ord(c2)+1):
yield chr(c)
df = pd.DataFrame()
for c in char_range('a', 'z'):
df[f'{c}'] = random.sample(range(10), 3) # Random Data
rearranged = random.sample(range(26), 26) # Random Order
df = df.iloc[:, rearranged]
print(df.iloc[:,:15]) # 15 Col View
for col in df.columns: # List of indices and columns
print(str(df.columns.get_loc(col)) + '\t' + col)

df.columns.get_indexer(['pear', 'apple'])
# Out: array([0, 1], dtype=int64)
如果索引中有非唯一的标签(列只支持唯一的标签)它接受与get_indexer相同的参数:
df = pd.DataFrame(
{"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]},
index=[0, 1, 1])
df.index.get_indexer_for([0, 1])
# Out: array([0, 1, 2], dtype=int64)
这两种方法也都支持使用,f.i.的非精确索引,浮点值取有容差的最近值。如果两个索引到指定标签的距离相同或重复,则选择索引值较大的索引:
df = pd.DataFrame(
{"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]},
index=[0, .9, 1.1])
df.index.get_indexer([0, 1])
# array([ 0, -1], dtype=int64)
DSM的解决方案是有效的,但是如果你想要一个直接等价的方法(df。Columns == name).nonzero()
当您希望找到多个列匹配时,可以使用使用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的答案,get_loc有一些奇怪的属性,这取决于当前版本Pandas(1.1.5)中的索引类型,因此根据您的索引类型,您可能会返回索引、掩码或切片。这对我来说有点令人沮丧,因为我不想仅仅为了提取一个变量的索引而修改整个列。更简单的方法是完全避免这个函数:
list(df.columns).index('pear')
非常简单,而且可能相当快。
这个怎么样:
df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
out = np.argwhere(df.columns.isin(['apple', 'orange'])).ravel()
print(out)
[1 2]