[英]How can I “merge” rows in a Pandas DataFrame based on these conditions
My dataFrame looks like this:我的 dataFrame 看起来像这样:
+---------------+------+--------+
| Date | Type | Number |
+---------------+------+--------+
| 14-March-2020 | A | 10 |
| 14-March-2020 | B | 20 |
| 14-March-2020 | C | 30 |
| 15-March-2020 | A | 40 |
| 15-March-2020 | B | 50 |
| 15-March-2020 | C | 60 |
+---------------+------+--------+
I want to transform it to:我想将其转换为:
+---------------+----+----+----+
| Date | A | B | C |
+---------------+----+----+----+
| 14-March-2020 | 10 | 20 | 30 |
| 15-March-2020 | 40 | 50 | 60 |
+---------------+----+----+----+
I have tried using df.groupby('Date') - for an initial condensation - however that doesn't seem to work.我尝试使用 df.groupby('Date') - 进行初始冷凝 - 但是这似乎不起作用。 Any help would be great.
任何帮助都会很棒。
A solution that removes also the index 'Type'
that remains after pivoting the dataframe involves rename_axis
after resetting the index.在旋转
rename_axis
后还删除索引'Type'
的解决方案涉及重置索引后的 rename_axis。
import pandas as pd
df.pivot('Date', 'Type', 'Number').reset_index().rename_axis(columns={'Type': ''})
# Date A B C
# 0 14-March-2020 10 20 30
# 1 15-March-2020 40 50 60
If we omit rename_axis
, we in fact obtain如果我们省略
rename_axis
,我们实际上得到
df.pivot('Date', 'Type', 'Number').reset_index()
# Type Date A B C
# 0 14-March-2020 10 20 30
# 1 15-March-2020 40 50 60
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.