我有一个带有MultiIndex的pandas DataFrame,我正在寻找一种为某些级别修改我的MultiIndex级别之一的子集的快速方法。这是一个示例,其中我需要更改两个索引(0、10)和(9、25)并更改其“结束”级别。
import pandas as pd
# Make up some data
data = pd.DataFrame({
'start': [0, 12, 9, 24],
'end': [10, 20, 25, 32],
'col1': ['a', 'b', 'a', 'd'],
'col2': [1, 1, 2, 2]
}).set_index(['start', 'end'])
# Idx to change for the "end" level
idx_to_change = {(0, 10), (9, 25)}
### A cumbersome way to do it ###
data.reset_index(inplace=True)
subset = [True if (s, t) in idx_to_change else False for (s, t, _, _) in data.values]
data.loc[subset, 'end'] += 10
# Update the data
data.set_index(['start', 'end'], inplace=True)
如您所见,更改一些索引需要一些代码(而且可能特别慢)。您知道更好的方法吗?
谢谢您的帮助
答案 0 :(得分:3)
一种方法是通过date
重新分配索引:
pd.MultiIndex
答案 1 :(得分:1)
可以将MultiIndex转换为数据帧,对其进行修改,然后将其重新分配为索引。
data = pd.DataFrame({
'start': [0, 12, 9, 24],
'end': [10, 20, 25, 32],
'col1': ['a', 'b', 'a', 'd'],
'col2': [1, 1, 2, 2]
}).set_index(['start', 'end'])
# extract & modify the index
idx = data.index.to_frame()
idx.loc[[(0,10), (9,25)], 'end'] += 10
# assign it back
# in more recent versions of pandas (0.24+) the MultiIndex can be created
# directly from the data frame
data.index = pd.MultiIndex.from_frame(idx[['start', 'end']])
# with earlier versions the trick is to convert the dataframe `idx` to
# desired MultiIndex
data.index = idx.reset_index(drop=True).set_index(['start','end']).index
data
# outputs
col1 col2
start end
0 20 a 1
12 20 b 1
9 35 a 2
24 32 d 2
答案 2 :(得分:0)
一种方法是,您可以将索引作为列表取出并在更新后重新分配;
idx_to_change = {(0, 10), (9, 25)}
as_list = data.index.tolist()
for idx_change in idx_to_change:
idx = as_list.index(idx_change)
as_list[idx] = (as_list[idx][0], list(as_list[idx])[1] + 10) #tuple is immutable so need to be converted to list
data.index = as_list
希望有帮助。