当索引不像auto_increment时如何获取熊猫行号。

时间:2018-09-04 09:17:59

标签: python pandas

df =

enter image description here

df.index[df.item == 'alcohol'][0]

它给了我45

我想要2

请提出建议。

4 个答案:

答案 0 :(得分:2)

使用pandas.Index.get_loc

var
  hashtbl, link: array of Int32;
  i, j: Integer;

...

SetLength(hashtbl, 65536);
SetLength(link, 131072);

for i := 0 to 65535 do
begin
  hashtbl[i] := -1;
end;

...

答案 1 :(得分:1)

过滤后使用索引:

df[df.item == 'alcohol'].index
Index(['row 2'], dtype='object')

如果您希望输出为2,则:

indices = df[df.item == 'alcohol'].index
indices.str[-1:]
Index(['2'], dtype='object')

如果需要列表:

indices.str[-1:].tolist()
['2']

如果行号超过1位,则使用:

indices.extract(r'(\d+)',expand=False)

初始设置:

df = pd.DataFrame({"index":[23,45,89],"item":['food','alcohol','drinks']},
                  index=['row 1','row 2','row 3'])
df

     index  item
row 1   23  food
row 2   45  alcohol
row 3   89  drinks

答案 2 :(得分:1)

如果可能,请通过reset_index创建默认索引值:

df = df.reset_index(drop=True)
out = df.index[df.item == 'alcohol'][0]
#generla solution if possible not matched values
out = next(iter(df.index[df.item == 'alcohol']), 'not matched')

解决方案可以使用任何索引值:

out = next(iter(np.where(df.item == 'alcohol')[0]), 'not matched')

示例:

df = pd.DataFrame({'item': ['food','alcohol','drinks']}, index=[23,45,89])
print (df)
       item
23     food
45  alcohol
89   drinks

#test your output
print (df.index[df.item == 'alcohol'][0])
45

#python counts from 0, so for second value get 1
out = next(iter(np.where(df.item == 'alcohol')[0]), 'not matched')
print (out)
1

#condition not matched, so returned empty DataFrame
out = next(iter(np.where(df.item == 'a')[0]), 'not matched')
print (out)
not matched

答案 3 :(得分:0)

df.loc[df['item']== 'alcohol'].index

它为您提供:

Index(['row 2'], dtype='object')

如果您想要“ iloc”位置:

value_to_find = df.loc[df['item']== 'alcohol'].index.tolist()[0]
row_indexes = df.index.tolist()
position = row_indexes.index(value)
print(position)

注意:索引从0开始,您发现1,对吗?如果要计数行

position = row_indexes.index(value) + 1