I would like to add column names to the results of a groupby on a DataFrame
in Python 3.6.
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.
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