【发布时间】:2026-02-23 11:15:01
【问题描述】:
在 R 中,当您需要根据可以执行的列名检索列索引时
idx <- which(names(my_data)==my_colum_name)
有没有办法对 pandas 数据帧做同样的事情?
【问题讨论】:
标签: python pandas dataframe indexing
在 R 中,当您需要根据可以执行的列名检索列索引时
idx <- which(names(my_data)==my_colum_name)
有没有办法对 pandas 数据帧做同样的事情?
【问题讨论】:
标签: python pandas dataframe indexing
当然,你可以使用.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"])),尽管我肯定可以看到您需要索引号的情况。
【讨论】:
.iloc 运算符时很有用,在这种情况下,行和列都只能传递整数。
DSM 的解决方案有效,但如果您想要直接等效于 which,您可以使用 (df.columns == name).nonzero()
【讨论】:
当您可能要查找多个列匹配项时,可以使用使用 searchsorted method 的矢量化解决方案。因此,使用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])
【讨论】:
这是通过列表理解的解决方案。 cols 是要为其获取索引的列列表:
[df.columns.get_loc(c) for c in cols if c in df]
【讨论】:
cols 的元素比df.columns 少,所以for c in cols if c in df 会更快。
如果您想要列位置中的列名(与 OP 问题相反),您可以使用:
>>> df.columns.get_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.get_values()[1]
'orange'
其他方式:
df.iloc[:,1].name
df.columns[location] #(thanks to @roobie-nuby for pointing that out in comments.)
【讨论】:
这个怎么样:
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]
【讨论】:
对于返回多个列索引,如果您有唯一标签,我建议使用pandas.Index 方法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_for。它采用与get_indeder 相同的参数:
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)
这两种方法还支持 非精确索引 with, 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 的答案,get_loc 有一些奇怪的属性,具体取决于当前版本的 Pandas (1.1.5) 中的索引类型,因此根据您的索引类型,您可能会得到一个索引、一个掩码、或一片。这对我来说有点令人沮丧,因为我不想仅仅为了提取一个变量的索引而修改整个列。更简单的是完全避免使用该功能:
list(df.columns).index('pear')
非常简单,可能相当快。
【讨论】:
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)
起作用。
ix = 'none'
try:
ix = list(df.columns).index('Col_X')
except ValueError as e:
ix = None
pass
if ix is None:
# do something
【讨论】: