猿问

如何在 pandas 中应用条件但仅适用于有限数量的行?

我有一个多索引的熊猫表,如下所示。

我想更新 Crop 和 Avl 列,例如使用“Tomato”和“0”,但仅限有限次数(例如,我只需要 10 行 Tomato,满足条件)。目前通过 pandas 我最终更新了满足该条件的所有行。


col1 = ildf1.index.get_level_values(1) # https://stackoverflow.com/a/50608928/9148067

cond = col1.str.contains('DN_Mega') & (ildf1['Avl'] == 1)


ildf1.iloc[ cond , [0,2]] = ['Tomato', 0]

如何将其限制为仅表示满足条件的所有行中的 10 行?


PS:我使用的是get_level_values因为我的 df 中有 4 列(GR、PP+MT、Bay、Row)多重索引。


森栏
浏览 97回答 1
1回答

幕布斯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
随时随地看视频慕课网APP

相关分类

Python
我要回答