为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

陪伴而非守候 2021-06-07 20:03:52
df =df.index[df.item == 'alcohol'][0]它给了我 45我想 2请建议。
查看完整描述

3 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

如果可能,通过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


查看完整回答
反对 回复 2021-06-09
?
www说

TA贡献1775条经验 获得超8个赞

使用pandas.Index.get_loc


IE


import pandas as pd

df = pd.DataFrame(columns = ['x'])

df.loc[10] = None

df.loc[20] = None

df.loc[30] = 1


print(df.index.get_loc(30))

>> 2


查看完整回答
反对 回复 2021-06-09
?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

过滤后使用索引:


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


查看完整回答
反对 回复 2021-06-09
  • 3 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号