首页 > 解决方案 > Pandas,Python:如何将行值转换为列并将另一列的值聚合为总和

问题描述

我正在尝试分析一个 covid 数据集,并且对如何通过 pandas 修复数据不知所措。数据集如下所示:

在此处输入图像描述

我试图让它看起来像这样:

              April 2                        | April 3                       | April 4 
unique_tests  total unique tests for april 2 | total unique tests for april 3|total unique tests for april 4 
positive      total positive for april 2     | total positive for april 3    |total positive for april 4 
negative      total negative for april 2     | total negative for april 3    |total negative for april 4 
remaining      total remaining for april 2   | total remaining for april 3   |total remaining for april 4 

我的日期截止到 4 月 24 日。

关于我如何实现这一点的任何想法?我无法使其与熊猫中的数据透视表一起使用

标签: pythonpandasdataset

解决方案


利用:

#convert columns to numeric and date to datetimes
df = pd.read_csv(file, thousands=',', parse_dates=['date'])
#create custom format of datetimes and aggregate sum, last transpose
df1 = df.groupby(df['date'].dt.strftime('%d-%b')).sum().T

或者是否可以重新分配date由新格式的日期时间填充的列:

df1 = df.assign(date = df['date'].dt.strftime('%d-%b')).groupby('date').sum().T

推荐阅读