gpt4 book ai didi

python - Pandas:multiIndex 数据帧上的部分索引不会重复行

转载 作者:行者123 更新时间:2023-12-03 23:07:04 25 4
gpt4 key购买 nike

我正在尝试使用 .loc 索引和标签列表从两级 Pandas MultiIndex 数据框中选择行(包括重复)。

但是,如果我尝试使用 MultiIndex 数据帧进行这种类型的索引,则输出的行顺序与输入的顺序相同,并且会忽略重复的索引。下面是一个例子:

import numpy as np
import pandas as pd
import string as s

index1 = list(s.ascii_uppercase[:4])
index2 = np.arange(2)
col_names='col1 col2 col3'.split()

new_slices = list('DDAB') # note order and repition of labels

multi_index = pd.MultiIndex.from_product([index1,index2],names=["level0","level1"])

data = np.arange(len(index1)*len(index2)*len(col_names))
data=data.reshape(len(index1)*len(index2),-1)


df2 = pd.DataFrame(data,columns=col_names,index=multi_index)

print(df2.loc[new_slices])

col1 col2 col3
level0 level1
A 0 0 1 2
1 3 4 5
B 0 6 7 8
1 9 10 11
D 0 18 19 20
1 21 22 23

我反而期望:
               col1  col2  col3
level0 level1
D 0 18 19 20
1 21 22 23
D 0 18 19 20
1 21 22 23
A 0 0 1 2
1 3 4 5
B 0 6 7 8
1 9 10 11

是否有我错过的 MultiIndex 特定功能?
还是我误解了 MultiIndex 中的级别是如何工作的?

(但是,这在从“常规”数据框中进行选择时按我的预期工作,例如:)
import numpy as np
import pandas as pd
import string as s

index1 = list(s.ascii_uppercase[:4])
col_names='col1 col2 col3'.split()

new_slices = list('DDAB') # note order and repition of labels

data1 = np.arange(len(index1)*len(col_names)).reshape(len(index1),-1)
df1 = pd.DataFrame(data1,columns=col_names,index=index1)

print(df1)
print(df1.loc[new_slices])

这给出了我期望的结果——一个包含 D、D、A、B 行的数据框。

最佳答案

以这种方式尝试

index1 = list(s.ascii_uppercase[:4])
index2 = np.arange(2)
col_names='col1 col2 col3'.split()

new_slices = list('DDAB') # note order and repition of labels

multi_index = pd.MultiIndex.from_product([index1,index2],names=["level0","level1"])

data = np.arange(len(index1)*len(index2)*len(col_names))
data=data.reshape(len(index1)*len(index2),-1)


df2 = pd.DataFrame(data,columns=col_names,index=multi_index)
df2.unstack().loc[new_slices].stack() # <=== this does the trick

enter image description here

关于python - Pandas:multiIndex 数据帧上的部分索引不会重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61870473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com