ak3*_*t0n 168 python indexing dataframe pandas
在R中,当您需要根据您可以执行的列的名称检索列索引时
idx <- which(names(my_data)==my_colum_name)
Run Code Online (Sandbox Code Playgroud)
有没有办法对pandas数据帧做同样的事情?
DSM*_*DSM 278
当然,你可以使用.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
Run Code Online (Sandbox Code Playgroud)
虽然说实话,我自己并不经常需要这个.通常按名称访问可以实现我想要的(df["pear"]
,df[["apple", "orange"]]
或者可能df.columns.isin(["orange", "pear"])
),尽管我可以肯定地看到你想要索引号的情况.
sno*_*vik 22
这是通过列表理解的解决方案.cols是获取索引的列的列表:
[df.columns.get_loc(c) for c in cols if c in df]
Run Code Online (Sandbox Code Playgroud)
Div*_*kar 10
当您可能希望找到多个列匹配时,可以使用使用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)]
Run Code Online (Sandbox Code Playgroud)
样品运行 -
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])
Run Code Online (Sandbox Code Playgroud)
Joe*_*moe 10
要稍微修改一下 DSM 的答案,get_loc
根据当前版本的 Pandas (1.1.5) 中的索引类型,有一些奇怪的属性,因此根据您的索引类型,您可能会得到索引、掩码或切片。这对我来说有点令人沮丧,因为我不想修改整个列只是为了提取一个变量的索引。更简单的是完全避免该函数:
list(df.columns).index('pear')
Run Code Online (Sandbox Code Playgroud)
非常简单,而且可能相当快。
如果您想要列位置的列名称(相反的OP问题),您可以使用:
>>> df.columns.get_values()[location]
Run Code Online (Sandbox Code Playgroud)
使用@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'
Run Code Online (Sandbox Code Playgroud)
其他方式:
df.iloc[:,1].name
Run Code Online (Sandbox Code Playgroud)
对于返回多个列索引,如果您有唯一标签,我建议使用该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)
Run Code Online (Sandbox Code Playgroud)
如果索引中有非唯一标签(列仅支持唯一标签)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)
Run Code Online (Sandbox Code Playgroud)
这两种方法还支持非精确索引,fi 用于浮点值,采用具有容差的最接近值。如果两个索引到指定标签的距离相同或重复,则选择索引值较大的索引:
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)
Run Code Online (Sandbox Code Playgroud)
小智 5
当该列可能存在或可能不存在时,则以下内容(上面的变体有效)。
ix = 'none'
try:
ix = list(df.columns).index('Col_X')
except ValueError as e:
ix = None
pass
if ix is None:
# do something
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
219002 次 |
最近记录: |