在R中,当您需要根据列名检索列索引时,您可以这样做
idx <- which(names(my_data)==my_colum_name)
有没有办法对熊猫数据框架做同样的事情?
在R中,当您需要根据列名检索列索引时,您可以这样做
idx <- which(names(my_data)==my_colum_name)
有没有办法对熊猫数据框架做同样的事情?
当前回答
DSM的解决方案是有效的,但是如果你想要一个直接等价的方法(df。Columns == name).nonzero()
其他回答
这个怎么样:
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]
更新:" 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.)
DSM的解决方案是有效的,但是如果你想要一个直接等价的方法(df。Columns == name).nonzero()
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