【发布时间】:2018-12-12 07:44:40
【问题描述】:
我想将列名添加到 Python 3.6 中 DataFrame 上的 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)
结果
timeIndex
1 1
2 0
Name: isZero, dtype: int64
看起来timeIndex 是一个列标题,但尝试按名称寻址列会产生异常。
df2['timeIndex']
# KeyError: 'timeIndex'
df2['isZero']
# KeyError: 'isZero'
我正在寻找这个结果。
df2
timeIndex isZero
0 1 1
1 2 0
df2['isZero']
0 1
1 0
【问题讨论】:
标签: python pandas dataframe pandas-groupby