假设我有下表:
from datetime import datetime
import pandas as pd
d = [[datetime(year=2021, month=1, day=1, minute=5), "A", "new", 3],
[datetime(year=2021, month=1, day=1, minute=5), "B", "new", 6],
[datetime(year=2021, month=1, day=1, minute=5), "C", "new", 7],
[datetime(year=2021, month=1, day=1, minute=15), "A", "old", 6],
[datetime(year=2021, month=1, day=1, minute=15), "B", "old", 2],
[datetime(year=2021, month=1, day=1, minute=15), "C", "old", 14],
]
df = pd.DataFrame(data=d, columns=["Time", "Article", "Status", "Qty"])
我想重组这些数据,每个“时间”值都有一行,然后对于每篇文章都有“数量”和“状态”列。
这我几乎可以使用pivot_table实现,如下所示:
pd.pivot_table(data=df, index=["Time"], columns=["Article"], values=["Status", "Qty"], aggfunc="last")
这为我产生以下输出:
数量 | 地位 | |||||
---|---|---|---|---|---|---|
文章 | 一种 | 乙 | C | 一种 | 乙 | C |
时间 | ||||||
2021-01-01 00:05:00 | 3 | 6 | 7 | 新的 | 新的 | 新的 |
2021-01-01 00:15:00 | 6 | 2 | 14 | 老的 | 老的 | 老的 |
但是,我希望这按文章分组,而不是按值列分组。所以就像它会由以下代码生成:
arrays = [
["A", "A", "B", "B", "C", "C", "qux", "qux"],
["Qty", "Status", "Qty", "Status", "Qty", "Status"],
]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=["Article", "Value"])
data_pivot=[
[3, "new", 6, "new", 6, "new"],
[6, "old", 2, "old", 14, "old"]
]
pd.DataFrame(data=data_pivot, columns=index, index=[datetime(year=2021, month=1, day=1, minute=5), datetime(year=2021, month=1, day=1, minute=15)])
文章 | 一种 | 乙 | C | |||
---|---|---|---|---|---|---|
价值 | 数量 | 地位 | 数量 | 地位 | 数量 | 地位 |
2021-01-01 00:05:00 | 3 | 新的 | 6 | 新的 | 6 | 新的 |
2021-01-01 00:15:00 | 6 | 老的 | 2 | 老的 | 14 | 老的 |
简单地在 pivot_table-call 中切换 values- 和 columns- 关键字也没有给我预期的输出。
不幸的是,我在命名这个问题时遇到了麻烦,所以我很难找到现有的解决方案(因此,这个问题的标题可能很奇怪),所以如果这已经被问过很多次,我很抱歉。
使用DataFrame.swaplevel
有DataFrame.sort_index
:
df = df.swaplevel(1,0,axis=1).sort_index(axis=1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句