我有以下分层数据的数据格式。可以有一个级别和可变深度的多行。我试图得到a结果,在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发布于 2020-04-29 18:27:23
最终,通过将col_1拆分为每个深度的列来解决这一问题。然后按每一列(深度1、2、..6)分组,并将所有结果数据连在一起。不太干净,但工作正常!
发布于 2020-04-24 17:09:38
我根据你的样本数据做了一些假设。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: int64https://stackoverflow.com/questions/61411327
复制相似问题