幕布斯6054654
对于如下定义的 df,您需要添加额外的索引来对具有不同编号的所有行进行计数,然后您可以基于切片设置新值。来啦=^..^=import pandas as pddf = pd.DataFrame({'Crop': ['', '', '', '', ''], 'IPR': ['', '', '', '', ''], 'Avi': [1, 2, 3, 4, 5]}, index=[['0','0', '8', '8', '8'], ['6', '7', '7', '7', '7']])# add additional indexdf['id'] = [x for x in range(0, df.shape[0])]df.set_index('id', append=True, inplace=True)# select only two values based on conditioncondition = df.index[df.index.get_level_values(0).str.contains('8')][0:2]df.loc[condition, ['Crop', 'IPR']] = ['Tomato', 0]输出: Crop IPR Avi id 0 6 0 1 7 1 28 7 2 Tomato 0 3 3 Tomato 0 4 4 5