Python 根据日期列将列移到行
我有一个数据框,看起来像: df1: 我希望将数据帧旋转为这样,以便可视化表格:Python 根据日期列将列移到行,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据框,看起来像: df1: 我希望将数据帧旋转为这样,以便可视化表格: +-------------+---------+------------+----------+---------------+---------------+ | date | death | positive | recovery | positive cum | recovery cum. | +-------------+---------+------------+-------
+-------------+---------+------------+----------+---------------+---------------+
| date | death | positive | recovery | positive cum | recovery cum. |
+-------------+---------+------------+----------+---------------+---------------+
| 2020-03-02 | 0 | 5 | 0 | 5 | 0 |
| 2020-03-03 | 0 | 10 | 0 | 15 | 0 |
+-------------+---------+------------+----------+---------------+---------------+
我试过:
pd.pivot_表(df,索引=['date'],列=['status'],值=['counts'],aggfunc='sum')
但是结果只取非nan日期的行。请首先通知
ffill
日期列中的NaN
值,然后使用pivot\u table
和aggfunc=First
重塑数据框:
pvt = df.assign(date=df['date'].ffill())\
.pivot_table(index='date', columns='status', values='counts', aggfunc='first')
或者,如果与特定的日期
对应的状态
中没有重复值,则可以使用透视
:
pvt = df.assign(date=df['date'].ffill()).pivot('date', 'status', 'counts')
pvt = df.assign(date=df['date'].ffill()).pivot('date', 'status', 'counts')
status death positive positive cum recovery recovery cum
date
2020-03-02 0 5 5 0 0
2020-03-03 0 10 15 0 0