我是Python&大熊猫。
我想在我的pandas数据帧中找到某个值的索引(比如security_id
),因为这是列开始的位置。
(列数上方的行数不明,行数不相关,左侧有一些空的“列”。)
据我所知,isin方法只返回值是否存在的布尔值,而不是索引。
如何找到此值的索引?
答案 0 :(得分:3)
假设您的DataFrame如下所示:
mysql> SHOW TABLES;
执行以下操作:
0 1 2 3 4
0 a er tfr sdf 34
1 rt tyh fgd thy rer
2 1 2 3 4 5
3 6 7 8 9 10
4 dsf wew security_id name age
5 dfs bgbf 121 jason 34
6 dddp gpot 5754 mike 37
7 fpoo werwrw 342 jack 31
答案 1 :(得分:2)
避免显式循环的oneliner解决方案...
返回整行
df.iloc [np.flatnonzero((df =='security_id')。values)// df.shape [1],:]
返回行和列
df.iloc [ np.flatnonzero((df =='security_id')。values)// df.shape [1], np.unique(np.flatnonzero((df =='security_id')。values)%df.shape [1]) ]
答案 2 :(得分:1)
您要查找的值不重复:
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')]
您将获得一个列表
答案 3 :(得分:0)
我认为here之前可能会问过这个问题。接受的答案非常全面,可以帮助您找到列中值的索引。
编辑: 如果该值所在的列未知,则可以使用:
for col in df.columns:
df[df[col] == 'security_id'].index.tolist()
答案 4 :(得分:0)
获取所有列中与搜索词匹配的行的索引
search = 'security_id'
df.loc[df.isin([search]).any(axis=1)].index.tolist()
针对所有列中的搜索词进行匹配过滤的行
search = 'search term'
df.loc[df.isin([search]).any(axis=1)]
答案 5 :(得分:0)
函数查找数据帧中值的位置
import pandas as pd
import numpy as np
def pandasFindPositionsInDataframe(dfIn,findme):
positions = []
irow =0
while ( irow < len(dfIn.index)):
list_colPositions=dfIn.columns[dfIn.iloc[irow,:]==findme].tolist()
if list_colPositions != []:
colu_iloc = dfIn.columns.get_loc(list_colPositions[0])
positions.append([irow, colu_iloc])
irow +=1
return positions