我有一个包含以下列的pandas数据框:
我该怎么做这两件事?
+--------+-----------+----------+--------+--+
| 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']
我一直在考虑如何使用融化,但我不太确定它是否适用于此背景。
谢谢!
答案 0 :(得分:1)
您可以将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
。数据 NOT 丢失,仅由,
加入并分隔:
print df1.pivot_table(index=['itemid', 'mymonth'], columns='c', values='d',aggfunc=', '.join)
.reset_index()
.rename_axis(None, axis=1)