1 回答
TA贡献1876条经验 获得超7个赞
对于如下定义的 df,您需要添加额外的索引来对具有不同编号的所有行进行计数,然后您可以基于切片设置新值。来啦=^..^=
import pandas as pd
df = pd.DataFrame({'Crop': ['', '', '', '', ''], 'IPR': ['', '', '', '', ''], 'Avi': [1, 2, 3, 4, 5]}, index=[['0','0', '8', '8', '8'], ['6', '7', '7', '7', '7']])
# add additional index
df['id'] = [x for x in range(0, df.shape[0])]
df.set_index('id', append=True, inplace=True)
# select only two values based on condition
condition = 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 2
8 7 2 Tomato 0 3
3 Tomato 0 4
4 5
添加回答
举报