python - 如何聚合 Pandas 中的多列?

标签 python pandas

我以前在这里问过类似的问题
How to get aggregate of data from multiple dates in pandas?
但我的问题稍微复杂一些。

import pandas as pd
import numpy as np

df = pd.DataFrame(data={'name':['a', 'b', 'c', 'd', 'e', 'f'],
                        'vaccine_1':['2021-01-20', '2021-01-20', '2021-02-20', np.nan, '2021-02-22', '2021-02-23'],
                        'vaccine_2':['2021-02-22', '2021-02-22', '2021-02-25', np.nan, '2021-03-22', np.nan], 
                        'vaccine_type': ['AZ', 'AZ', 'AZ', np.nan, 'Sinovac', 'Sinovac'],
                        'gender':['F', 'M', 'F', 'F', 'M', 'M']})

df['vaccine_1'] = pd.to_datetime(df['vaccine_1']).dt.date
df['vaccine_2'] = pd.to_datetime(df['vaccine_2']).dt.date
df
我想要一张包含类似内容的表格。
date | F | M | vaccine_type | vaccine_1_total | vaccine_2_total |
我的原始表格比这更复杂,数据更多,但我认为总结了我的意思。
多亏了我上一个问题的答案,我可以使用 Pandas Melt 获得正确的日期。
out = df.melt(var_name='vaccine', value_name='date', value_vars=['vaccine_1', 'vaccine_2'])
print(pd.crosstab(out['date'], out['vaccine']))
输出:
vaccine     vaccine_1  vaccine_2
date 
2021-01-20          2          0
2021-02-20          1          0
2021-02-22          1          2
2021-02-23          1          0
2021-02-25          0          1
2021-03-22          0          1
但我不知道如何修改它以使其适合我的需要。任何的想法?谢谢。
编辑:
所需的数据帧
date        | F | M | vaccine_type | vaccine_1_total | vaccine_2_total 
'2021-01-20'| 1 | 1 | AZ           | 2               | 0 
'2021-02-20'| 1 | 0 | AZ           | 1               | 0 
'2021-02-22'| 1 | 1 | AZ           | 1               | 1 
'2021-02-22'| 1 | 0 | Sinovac      | 1               | 0  
等等
所以我觉得应该是groupby和melt的结合吧?我可以使用 groupby 来获取非日期列,但是如何将其与melt 结合起来呢?

最佳答案

您可以先创建一个表,其中包含性别和疫苗_x 的组合计数,然后合并不同指标的总和:

df2 = (df.melt(id_vars=['gender', 'vaccine_type'],
               value_vars=['vaccine_1', 'vaccine_2'],
               var_name='vaccine', value_name='date')
         .groupby(['date', 'vaccine_type', 'gender']).agg({'vaccine': 'value_counts'})
         .rename(columns={'vaccine': 'count'})
         .reset_index()
         .pivot_table(index=['date', 'vaccine_type'], columns=['gender', 'vaccine'], values='count', fill_value=0)
        )

pd.merge(df2.sum(level=0, axis=1).reset_index(),
         df2.sum(level=1, axis=1).reset_index(),
         on=['date', 'vaccine_type']
        )
输出:
         date vaccine_type  F  M  vaccine_1  vaccine_2
0  2021-01-20           AZ  1  1          2          0
1  2021-02-20           AZ  1  0          1          0
2  2021-02-22           AZ  1  1          0          2
3  2021-02-22      Sinovac  0  1          1          0
4  2021-02-23      Sinovac  0  1          1          0
5  2021-02-25           AZ  1  0          0          1
6  2021-03-22      Sinovac  0  1          0          1
中间输出(df2):
gender                          F                   M          
vaccine                 vaccine_1 vaccine_2 vaccine_1 vaccine_2
date       vaccine_type                                        
2021-01-20 AZ                   1         0         1         0
2021-02-20 AZ                   1         0         0         0
2021-02-22 AZ                   0         1         0         1
           Sinovac              0         0         1         0
2021-02-23 Sinovac              0         0         1         0
2021-02-25 AZ                   0         1         0         0
2021-03-22 Sinovac              0         0         0         1

关于python - 如何聚合 Pandas 中的多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69009118/

相关文章:

python - 如何使用滚动汇总功能控制 pandas groupby 返回的索引

python - 如何使用Python在excel上打印开始时间和结束时间?

pandas - 如何将 bool 值的数据帧转换为 1 和 np.NaN 的数据帧?

python - 从 pandas 数据帧加载 Keras 中的批量图像

python - <class 'datetime.time' > 不可转换为日期时间

python - 使用 python 拟合指数函数

python - 如何在 pandas 中分组和处理优先级提取

python - R 用户的 matplotlib?

python - 计算与 Pandas 匹配的字符串和数字的行数

python - 如何使用包含过滤数据帧 DatetimeIndex