python - 根据日期列取列到行
问题描述
我有一个看起来像的数据框:
df1:
+-------------+-------------------+------------+
| date | status | counts |
+-------------+-------------------+------------+
| 2020-03-02 | death | 0 |
| nan. | positive | 5 |
| nan. | recovery | 0 |
| nan. | positive cum | 5 |
| nan. | recovery cum | 0 |
| 2020-03-03 | death | 0 |
| nan. | positive | 10 |
| nan. | recovery | 0 |
| nan. | positive cum | 15 |
| nan. | recovery cum | 0 |
+-------------+-------------------+------------+
我想像这样旋转数据框以可视化表格:
+-------------+---------+------------+----------+---------------+---------------+
| 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_table(df, index=['date'], columns=['status'], values=['counts'], aggfunc='sum')
但结果只取非nan日期的行。请指教
解决方案
首先列中ffill
的NaN
值,date
然后使用pivot_table
withaggfunc=first
来重塑数据框:
pvt = df.assign(date=df['date'].ffill())\
.pivot_table(index='date', columns='status', values='counts', aggfunc='first')
或者,如果没有status
对应于特定的重复值,date
您可以改用pivot
:
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
推荐阅读
- linux - 安装 Openfst Thrax 时出错 [配置:错误:未找到 fst/fst.h 标头]
- java - 为什么此堆排序方法适用于
但不带通配符? - java - 在当前类中使用非创建类
- javascript - 未捕获的类型错误:babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__.Observable 不是构造函数
- python-3.x - 如何从字典列表中返回字符串
- python - 停止 SSHTunnel 服务器时,应用程序挂起
- python - 如何通过 python 获取给定库路径的 Perforce 文件类型?
- java - 将两个变量传递给一个方法以获得两个结果
- javascript - 如何使用带有事件的路由器链接?
- git - 如何将公共 repo 的分支设为私有并与 github.com 上的原始 repo 进行比较