猿问

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

df =

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

它给了我 45

我想 2

请建议。


陪伴而非守候
浏览 180回答 3
3回答

BIG阳

如果可能,通过reset_index以下方式创建默认索引值:df = df.reset_index(drop=True)out = df.index[df.item == 'alcohol'][0]#generla solution if possible not matched valuesout = 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)       item23     food45  alcohol89   drinks#test your outputprint (df.index[df.item == 'alcohol'][0])45#python counts from 0, so for second value get 1out = next(iter(np.where(df.item == 'alcohol')[0]), 'not matched')print (out)1#condition not matched, so returned empty DataFrameout = next(iter(np.where(df.item == 'a')[0]), 'not matched')print (out)not matched

www说

使用pandas.Index.get_locIEimport pandas as pddf = pd.DataFrame(columns = ['x'])df.loc[10] = Nonedf.loc[20] = Nonedf.loc[30] = 1print(df.index.get_loc(30))>> 2

江户川乱折腾

过滤后使用索引:df[df.item == 'alcohol'].indexIndex(['row 2'], dtype='object')如果您希望输出为2:indices = df[df.item == 'alcohol'].indexindices.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  itemrow 1   23  foodrow 2   45  alcoholrow 3   89  drinks
随时随地看视频慕课网APP

相关分类

Python
我要回答