Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 每天统计数据帧中的实例数_Python_Pandas_Dataframe_Group By - Fatal编程技术网

Python 每天统计数据帧中的实例数

Python 每天统计数据帧中的实例数,python,pandas,dataframe,group-by,Python,Pandas,Dataframe,Group By,我有一个数据帧 df = pd.DataFrame(data=[[1,0],[1,0],[2,0],[2,1]],columns=['day','class']) 我想每天数一数1班的实例。我这样使用groupby df.groupby(['class','day'])['class'].count() Out[51]: day class 1 0 2 2 0 1 1 1 Name: class, dtype: int64

我有一个数据帧

df = pd.DataFrame(data=[[1,0],[1,0],[2,0],[2,1]],columns=['day','class'])
我想每天数一数1班的实例。我这样使用groupby

df.groupby(['class','day'])['class'].count()

Out[51]: 
day  class
1    0        2
2    0        1
     1        1
Name: class, dtype: int64
但我也希望在第1天第1课中没有任何实例:

Out[51]: 
day  class
1    0        2
     1        0
2    0        1
     1        1
Name: class, dtype: int64
添加参数
fill_value=0
和:


使用pivot_表,即使不如jezrael的解决方案优雅:

df['class1'] = df['class']
df = df.pivot_table(index='class', columns='day', values='class1',
                 fill_value=0, aggfunc='count').unstack()
输出:

day  class
1    0        2
     1        0
2    0        1
     1        1

这里有一个方法。类别确保在执行
groupby
操作时,保持每个组合

这是一个更面向数据而不是面向操作的解决方案

df = pd.DataFrame(data=[[1,0], [1,0], [2,0], [2,1]],
                  columns=['day', 'class'],
                  dtype='category')

df['count'] = 1
res = df.groupby(['class', 'day'], as_index=False)['count'].sum()
res['count'] = res['count'].fillna(0)

#   class day  count
# 0     0   1    2.0
# 1     0   2    1.0
# 2     1   1    0.0
# 3     1   2    1.0
可能重复的
df = pd.DataFrame(data=[[1,0], [1,0], [2,0], [2,1]],
                  columns=['day', 'class'],
                  dtype='category')

df['count'] = 1
res = df.groupby(['class', 'day'], as_index=False)['count'].sum()
res['count'] = res['count'].fillna(0)

#   class day  count
# 0     0   1    2.0
# 1     0   2    1.0
# 2     1   1    0.0
# 3     1   2    1.0