如何基于多重索引值修改DataFrame列值:将Deliveries_faced为5时的S/R设为0
解决方法:修改多重索引DataFrame中指定索引值的列数据
嘿,这事儿不难搞定,我给你两种实用的方法,根据你的习惯选就行~
首先先把你的原始DataFrame用代码还原出来,方便后续操作:
import pandas as pd # 构建你的原始多重索引DataFrame data = { 'S/R': [20, 45, 30, 55, 34, 27], 'Batfast_id': ['bfs_1', 'bfs_1', 'bfs_1', 'bfs_2', 'bfs_2', 'bfs_2'], 'Session_no': [1, 1, 1, 1, 1, 1], 'Event_Name': ['fulham', 'fulham', 'fulham', 'gps', 'gps', 'gps'], 'Overs': [0, 1, 2, 0, 1, 2], 'Deliveries_faced': [5, 11, 17, 5, 11, 17] } df = pd.DataFrame(data).set_index(['Batfast_id', 'Session_no', 'Event_Name', 'Overs', 'Deliveries_faced'])
方法1:直接在多重索引上操作(高效推荐)
利用get_level_values方法定位到Deliveries_faced这个索引层级,筛选出值为5的行,然后直接修改S/R列:
# 筛选Deliveries_faced为5的行,将对应S/R设为0 df.loc[df.index.get_level_values('Deliveries_faced') == 5, 'S/R'] = 0
方法2:重置索引后修改(直观易理解)
如果你对多重索引操作不太熟悉,可以先把索引重置为普通列,修改后再恢复多重索引:
# 重置索引为普通列 df_reset = df.reset_index() # 筛选Deliveries_faced为5的行,修改S/R列 df_reset.loc[df_reset['Deliveries_faced'] == 5, 'S/R'] = 0 # 重新设置多重索引 df = df_reset.set_index(['Batfast_id', 'Session_no', 'Event_Name', 'Overs', 'Deliveries_faced'])
修改后的结果
执行任意一种方法后,你的DataFrame会变成这样:
S/R Batfast_id Session_no Event_Name Overs Deliveries_faced bfs_1 1 fulham 0 5 0 1 11 45 2 17 30 bfs_2 1 gps 0 5 0 1 11 34 2 17 27
内容的提问来源于stack exchange,提问作者Yoseph Ismail
相关产品推荐
相关产品推荐

