在R中,当您需要根据列名检索列索引时,您可以这样做

idx <- which(names(my_data)==my_colum_name)

有没有办法对熊猫数据框架做同样的事情?


当前回答

对于返回多列索引,我建议使用pandas。索引方法get_indexer,如果你有唯一的标签:

df = pd.DataFrame({"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]})
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)

其他回答

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)

![结果](结果

对于返回多列索引,我建议使用pandas。索引方法get_indexer,如果你有唯一的标签:

df = pd.DataFrame({"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]})
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)

当然,你可以使用.get_loc():

In [45]: df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

In [46]: df.columns
Out[46]: Index([apple, orange, pear], dtype=object)

In [47]: df.columns.get_loc("pear")
Out[47]: 2

尽管说实话,我自己并不经常需要这个。通常通过名称进行访问(df["pear"], df[["apple", "orange"]]),或者可能是df.columns。isin(["orange", "pear"]))),尽管我可以肯定地看到您想要索引号的情况。

更新:" 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]