熊猫-将列名称添加到groupby的结果中

Jac*_*rry 2 python dataframe pandas pandas-groupby

我想DataFrame在Python 3.6 中将列名添加到groupby的结果中。

我尝试了这段代码:

import pandas as pd
d = {'timeIndex': [1, 1, 1, 1, 2, 2, 2], 'isZero': [0,0,0,1,0,0,0]}
df = pd.DataFrame(data=d)
df2 = df.groupby(['timeIndex'])['isZero'].sum()
print(df2)
Run Code Online (Sandbox Code Playgroud)

结果

timeIndex
1    1
2    0
Name: isZero, dtype: int64
Run Code Online (Sandbox Code Playgroud)

看起来像是timeIndex列标题,但是尝试按名称寻址列会产生异常。

df2['timeIndex']
# KeyError: 'timeIndex'

df2['isZero']
# KeyError: 'isZero'
Run Code Online (Sandbox Code Playgroud)

我正在寻找这个结果。

df2 

     timeIndex    isZero
0    1    1
1    2    0

df2['isZero']

0    1
1    0
Run Code Online (Sandbox Code Playgroud)

sac*_*cuL 6

方法1:

as_index = False在您的中使用参数groupby

df2 = df.groupby(['timeIndex'], as_index=False)['isZero'].sum()

>>> df2
   timeIndex  isZero
0          1       1
1          2       0

>>> df2['isZero']
0    1
1    0
Name: isZero, dtype: int64
Run Code Online (Sandbox Code Playgroud)

方法2:

您可以使用to_frame所需的列名,然后reset_index

df2 = df.groupby(['timeIndex'])['isZero'].sum().to_frame('isZero').reset_index()

>>> df2
   timeIndex  isZero
0          1       1
1          2       0

>>> df2['isZero']
0    1
1    0
Name: isZero, dtype: int64
Run Code Online (Sandbox Code Playgroud)