Python DataFrame指定列转置:保留Date列,按Name重组表格
问题:如何按指定规则转置Pandas DataFrame?
输入DataFrame
| Name | Date | Score | Target | Difference |
|---|---|---|---|---|
| Jim | 2023-10-09 | 9 | 12 | 3 |
| Jim | 2023-10-16 | 13 | 16 | 3 |
| Andy | 2023-10-09 | 7 | 7 | 0 |
| Andy | 2023-10-16 | 5 | 20 | 15 |
生成该DataFrame的代码:
import pandas as pd df = pd.DataFrame({ 'Name': ["Jim","Jim","Andy", "Andy"], 'Date': ['2023-10-09', '2023-10-16', '2023-10-09', "2023-10-16"], 'Score': ["9","13","7", "5"], 'Target': ["12","16","7", "20"], 'Difference': ["3","3","0", "15"] })
需求说明
需要将DataFrame按Name列转置,把Score、Target、Difference作为Category行,Date作为分组列,得到如下预期输出:
| Date | Category | Jim | Andy |
|---|---|---|---|
| 2023-10-09 | Score | 9 | 7 |
| Target | 12 | 7 | |
| Difference | 3 | 0 | |
| 2023-10-16 | Score | 13 | 5 |
| Target | 16 | 20 | |
| Difference | 3 | 15 |
直接使用df.T无法得到预期结果,需采用正确的结构重塑方法。
解决方案
通过堆叠、拆分多层索引的方式实现结构转换,具体代码如下:
# 设置多层索引并堆叠列,再将Name层级转为列 df_transformed = df.set_index(['Name', 'Date']).stack().unstack(level='Name') # 重置索引,拆分多层索引为普通列 df_transformed = df_transformed.reset_index() # 重命名列名匹配预期输出 df_transformed.columns = ['Date', 'Category', 'Jim', 'Andy'] # 处理Date列重复值,仅保留每组第一个Category对应的日期 df_transformed['Date'] = df_transformed['Date'].where(df_transformed['Category'] == 'Score', '') print(df_transformed)
运行后即可得到与预期完全一致的表格结构。
内容的提问来源于stack exchange,提问作者PineNuts0
相关产品推荐
相关产品推荐

