If the data frame has 3 columns, I found this StackOverflow answer that gives zero counts: Pandas groupby for zero values
But, HOW to do this for the data frame having only two columns:
Question
NOTE: Answer preferable in Chain operations:
import numpy as np
import pandas as pd
df = pd.DataFrame({'date': pd.date_range('2018-01-01', periods=6),
'a': range(6),
})
df.iloc[2,0] = df.iloc[1,0]
print(df)
date a
0 2018-01-01 0
1 2018-01-02 1
2 2018-01-02 2
3 2018-01-04 3
4 2018-01-05 4
5 2018-01-06 5
To geth the counts of a I do this:
df1 = (df.query("a > 0")
.groupby(['date'])[['a']]
.count()
.add_suffix('_count')
.reset_index()
)
print(df1)
date a_count
0 2018-01-02 2
1 2018-01-04 1
2 2018-01-05 1
3 2018-01-06 1
Required Answer from Chain operation
date a_count
0 2018-01-01 0 # also include this row
0 2018-01-02 2
1 2018-01-04 1
2 2018-01-05 1
3 2018-01-06 1
My attempt:
df1 = (df.query("a > 0")
.groupby(['date'])[['a']]
.count()
.add_suffix('_count')
.unstack(fill_value=0)
.to_frame()
.stack()
.reset_index()
)
print(df1)
level_0 date level_2 0
0 a_count 2018-01-02 0 2
1 a_count 2018-01-04 0 1
2 a_count 2018-01-05 0 1
3 a_count 2018-01-06 0 1
This does not work.
How to fix this ?
Related links:
Pandas groupby for zero values