熊猫逗号分隔的层次结构分组和

问题描述 投票:1回答:2

我具有以下分层数据的数据格式。单个级别和可变深度可以有多行。我试图得到一个结果,其中在col_2中我们看到了该实例的所有下等级别的总和。

使用简单的groupby不起作用,因为它不了解层次结构。我尝试将col_1分为多个列,分别命名为1级到6级(深度),因此将1级分组到6级,但是尽管数据帧是多索引的,但结果仍然不正确。

分离前的代码:df.groupby(["col_1"], as_index=False).sum()

分离后的代码:df.groupby(["level-1","level-2","level-3","level-4","level-5","level-6"], as_index=False).sum()

任何帮助将不胜感激!

到目前为止感谢@Yo_Chris:

import pandas as pd
# sample data
df = pd.DataFrame({'Col1': ['PUU', 'PUU;UT', 'PUU;UT', 'PUU;UT;AHU', 'PUU;UT;AHU;CSP', 'PUU;AS', 'PUU;PREV', 'PUU;TECHNOLOGY', 'PUU;TECHNOLOGY', 'PUU;TECHNOLOGY;SPEC'],
                  'Col2': [1000,1000,50,500,250,100,1000,300,500,900]})

# groupby, sum and invert 
s = df.groupby('Col1')['Col2'].sum()[::-1]
# groupby, cumsum and invert
s.groupby(s.index.str[0]).cumsum()[::-1])```

# this results in the following:

Col1
PUU                    5600
PUU;AS                 4600
PUU;PREV               4500
PUU;TECHNOLOGY         3500
PUU;TECHNOLOGY;SPEC    2700
PUU;UT                 1800
PUU;UT;AHU              750
PUU;UT;AHU;CSP          250
Name: Col2, dtype: int64

而我们想要的是:

PUU                    5600
PUU;AS                  100
PUU;PREV               1000
PUU;TECHNOLOGY         1700
PUU;TECHNOLOGY;SPEC     900
PUU;UT                 1800
PUU;UT;AHU              750
PUU;UT;AHU;CSP          250
python-3.x pandas pandas-groupby hierarchical-data multi-index
2个回答
1
投票

我根据您的样本数据做出了一些假设。 col1始终是一个用分号分隔的单个字符,并且col1始终进行排序:col1不能为['a;b;c', 'a', 'a;b'...]

# sample data
df = pd.DataFrame({'Col1': ['a', 'a;b', 'a;b', 'a;b;c', 'a;b;c;d', 'e', 'f', 'g', 'g', 'g;h'],
                  'Col2': [1000,1000,50,500,250,100,1000,300,500,900]})

# groupby, sum and invert 
s = df.groupby('Col1')['Col2'].sum()[::-1]
# groupby, cumsum and invert
s.groupby(s.index.str[0]).cumsum()[::-1]

# return a pd.Series

Col1
a          2800
a;b        1800
a;b;c       750
a;b;c;d     250
e           100
f          1000
g          1700
g;h         900
Name: Col2, dtype: int64

0
投票

最终通过将col_1拆分为每个深度的单独列来解决此问题。然后按每列(深度1、2,.. 6)分组,并合并所有结果数据框。不是很干净,但是可以正常工作!

© www.soinside.com 2019 - 2024. All rights reserved.