在Pandas中以一系列方式存储groupby组

2024-09-30 18:35:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试加入熊猫的两个数据集。我要做的是将df2.groupby('BuildingID')的结果放入df1中的一个新系列中。原因是building ID是我将要使用的级别,而ItemID是建筑中的项的集合。在

示例:

df1
BuildingID  Blah    ...
3   'a' ...
4   'b' ...
5   'c' ...
7   'd' ...

df2
ItemID  BuildingID  EnergyID    ...
7   3   2   ...
11  3   11  ...
12  3   12  ...
13  4   2   ...
14  5   12  ...
15  4   10  ...
16  7   2   ...
17  7   3   ...

最后我要说的是:

^{pr2}$

所以我的问题是1,我如何实现这一点,2,这是一个好主意还是有更好的方法来表示这些数据-也许每个组的所有标题都有后缀的标题?在


Tags: 数据id标题示例原因级别df1blah
1条回答
网友
1楼 · 发布于 2024-09-30 18:35:33

这可能有点取决于你下一步想做什么,但我会选择类似于:

from StringIO import StringIO
import pandas as pd

indf1 = StringIO("""BuildingID  Blah
3   'a'
4   'b'
7   'c'
7   'd'
7   'x'""")    

indf2 = StringIO("""ItemID  BuildingID  EnergyID
7   3   2
11  3   11
12  3   12
13  4   2
14  5   12
17  4   10
17  7   2
17  7   3
17  7   4""")

df1 = pd.read_csv(indf1, delim_whitespace=True, index_col='BuildingID')
df2 = pd.read_csv(indf2, delim_whitespace=True, index_col='ItemID')

dfboth = df1.merge(df2, right_on='BuildingID', left_index=True, how='left')

dfboth.set_index('BuildingID', append=True, inplace=True)
dfboth.reorder_levels(['BuildingID', 'ItemID'])

                  Blah  EnergyID
BuildingID ItemID               
3          7       'a'         2
           11      'a'        11
           12      'a'        12
4          13      'b'         2
           17      'b'        10
7          17      'c'         2
           17      'c'         3
           17      'c'         4
           17      'd'         2
           17      'd'         3
           17      'd'         4
           17      'x'         2
           17      'x'         3
           17      'x'         4

相关问题 更多 >