Pandas - 将列名添加到 groupby 的结果中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51163975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas - Add Column Name to Results of groupby
提问by Jacob Quisenberry
I would like to add column names to the results of a groupby on a DataFrame
in Python 3.6.
我想将列名添加到DataFrame
Python 3.6中 a 上的 groupby 的结果中。
I tried this code:
我试过这个代码:
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)
Result
结果
timeIndex
1 1
2 0
Name: isZero, dtype: int64
It looks like timeIndex
is a column heading, but attempts to address a column by name produce exceptions.
它看起来像是timeIndex
一个列标题,但尝试按名称寻址列会产生异常。
df2['timeIndex']
# KeyError: 'timeIndex'
df2['isZero']
# KeyError: 'isZero'
I am looking for this result.
我正在寻找这个结果。
df2
timeIndex isZero
0 1 1
1 2 0
df2['isZero']
0 1
1 0
回答by sacuL
Method 1:
方法一:
use the argument as_index = False
in your groupby
:
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
Method 2:
方法二:
You can use to_frame
with your desired column name and then reset_index
:
您可以使用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