我有一个带有这些列的 pandas 数据框:
- 项目编号
- 2015 年 1 月 15 日状态
- 2015 年 1 月 15 日地点
- 2015 年 2 月 15 日状态
- 2015 年 2 月 15 日地点
- 等等
我该如何做这两件事?
- 创建多索引列,其中第一个索引是月份,第二个索引是我正在跟踪的指标(状态、位置)
- 堆叠列,使表格看起来像这样:
+--------+-----------+----------+--------+--+
| itemid | mymonth | location | status | |
+--------+-----------+----------+--------+--+
| A | 15/1/2015 | North | Good | |
| A | 15/2/2015 | South | Bad | |
+--------+-----------+----------+--------+--+
从如下所示的输入开始:
+--------+-------------------+---------------------+-------------------+---------------------+
| itemid | 15/01/2015 status | 15/01/2015 location | 15/02/2015 status | 15/02/2015 location |
+--------+-------------------+---------------------+-------------------+---------------------+
| A | Good | North | Bad | South |
+--------+-------------------+---------------------+-------------------+---------------------+
可以使用以下命令重新创建(输入):
import pandas as pd
df=pd.DataFrame()
df['itemid']=['A']
df['15/01/2015 status'] = ['Good']
df['15/01/2015 location'] = ['North']
df['15/02/2015 status'] = ['Bad']
df['15/02/2015 location'] = ['South']
我一直在考虑如何使用melt,但我不太确定它是否适用于这种情况。
最佳答案
您可以使用stack
与 split
最后pivot_table
与 rename_axis
(pandas
0.18.0
中的新功能):
df1 = df.set_index('itemid').stack().reset_index()
df1.columns = ['itemid','mymonth', 'd']
df1[['mymonth','c']] = df1.mymonth.str.split('\s+').apply(pd.Series)
print df1
itemid mymonth d c
0 A 15/01/2015 Good status
1 A 15/01/2015 North location
2 A 15/02/2015 Bad status
3 A 15/02/2015 South location
print df1.pivot_table(index=['itemid', 'mymonth'], columns='c', values='d', aggfunc='first')
.reset_index()
.rename_axis(None, axis=1)
itemid mymonth location status
0 A 15/01/2015 North Good
1 A 15/02/2015 South Bad
编辑:
我认为,如果通过 first
聚合,有时可能会丢失数据,因为您只带来第一个值(如果创建新索引的列中存在重复),而其他值会丢失。
所以如果通过字符串聚合,可以使用join
。数据不会丢失,只是通过,
连接和分隔:
print df1.pivot_table(index=['itemid', 'mymonth'], columns='c', values='d',aggfunc=', '.join)
.reset_index()
.rename_axis(None, axis=1)
关于python - Pandas: reshape 和多索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37053186/