Indexing 在熊猫中,如何获得已知值的索引?
如果我们在一列中有一个已知的值,我们如何得到它的索引值?例如:Indexing 在熊猫中,如何获得已知值的索引?,indexing,pandas,Indexing,Pandas,如果我们在一列中有一个已知的值,我们如何得到它的索引值?例如: In [148]: a = pd.DataFrame(np.arange(10).reshape(5,2),columns=['c1','c2']) In [149]: a Out[149]: c1 c2 0 0 1 1 2 3 2 4 5 ........ 我们知道,我们可以通过对应的索引得到一个值,如下所示 In [151]: a.ix[0,1] In [152]: a.c2[0]
In [148]: a = pd.DataFrame(np.arange(10).reshape(5,2),columns=['c1','c2'])
In [149]: a
Out[149]:
c1 c2
0 0 1
1 2 3
2 4 5
........
我们知道,我们可以通过对应的索引得到一个值,如下所示
In [151]: a.ix[0,1] In [152]: a.c2[0] In [154]: a.c2.ix[0] <-- use index
Out[151]: 1 Out[152]: 1 Out[154]: 1 <-- get value
In[151]:a.ix[0,1]In[152]:a.c2[0]In[154]:a.c2.ix[0]您的值可能有多个索引映射,返回列表更有意义:
In [48]: a
Out[48]:
c1 c2
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
In [49]: a.c1[a.c1 == 8].index.tolist()
Out[49]: [4]
另一种方法是使用numpy.where():
使用.loc[]访问器:
In [25]: a.loc[a['c1'] == 8].index[0]
Out[25]: 4
还可以通过将“c1”设置为索引来使用get_loc()。这不会更改原始数据帧
In [17]: a.set_index('c1').index.get_loc(8)
Out[17]: 4
要按值获取索引,只需在查询末尾添加.index[0]。这将返回结果第一行的索引
因此,应用于您的数据帧:
In [1]: a[a['c2'] == 1].index[0] In [2]: a[a['c1'] > 7].index[0]
Out[1]: 0 Out[2]: 4
当查询返回多行时,可以通过指定所需索引来访问附加索引结果,例如.index[n]
In [3]: a[a['c2'] >= 7].index[1] In [4]: a[(a['c2'] > 1) & (a['c1'] < 8)].index[2]
Out[3]: 4 Out[4]: 3
[3]中的a[a['c2']>=7]。[4]中的索引[1]:a[(a['c2']>1)和(a['c1']<8)]。索引[2]
Out[3]:4 Out[4]:3
我认为这可能对您有所帮助,包括索引和列值
您要查找的值不重复:
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
value=poz.iloc[0,0]
index=poz.index.item()
column=poz.columns.item()
您可以获取它的索引和列
重复:
matrix=pd.DataFrame([[1,1],[1,np.NAN]],index=['q','g'],columns=['f','h'])
matrix
Out[83]:
f h
q 1 1.0
g 1 NaN
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
index=poz.stack().index.tolist()
index
Out[87]: [('q', 'f'), ('q', 'h'), ('g', 'f')]
你会得到一个列表一个索引可以有非唯一的条目,为什么你说返回一个列表更有意义?嗯,我想这是我的错。如果所有索引都是唯一的,我们可以通过a.c1[a.c1==8].index.tolist()[0]
获得单个索引。谢谢您的回答,这是一个很好的理想选择。我没有考虑过索引对象可以转换为普通列表。谢谢阿加金。@waitingkuo是他们在2017年发布的获取索引的复杂方法吗?@waitingkuo如果我们想插入两个条件,我们怎么做?比如a.c1[a.c1==8]。不适用于此示例,但请想象a.c2==10是否也存在
matrix=pd.DataFrame([[1,1],[1,np.NAN]],index=['q','g'],columns=['f','h'])
matrix
Out[83]:
f h
q 1 1.0
g 1 NaN
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
index=poz.stack().index.tolist()
index
Out[87]: [('q', 'f'), ('q', 'h'), ('g', 'f')]