亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號