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

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

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

森栏 2023-08-22 10:25:20
我有一个多索引的熊猫表,如下所示。我想更新 Crop 和 Avl 列,例如使用“Tomato”和“0”,但仅限有限次数(例如,我只需要 10 行 Tomato,满足条件)。目前通过 pandas 我最终更新了满足该条件的所有行。col1 = ildf1.index.get_level_values(1) # https://stackoverflow.com/a/50608928/9148067cond = 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)多重索引。
查看完整描述

1 回答

?
幕布斯6054654

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


查看完整回答
反对 回复 2023-08-22
  • 1 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信