2016-07-20 3 views
3

私はpandas DataFrame次があります。ここではパンダデータフレームのピボット

  id    quantity cost type 
2016-06-18 1700057817  2   2383 A 
2016-06-18 1700057817  1   744 B 
2016-06-19 1700057817  5   934 A 

、日付はindexです。

を私はpivotの多くの用途を試してみた:私がこれまで試したどのような

  id   A-quantity A-cost B-quantity B-cost 
2016-06-18 1700057817 2   2383 1   744 
2016-06-19 1700057817 5   934  NA   NA 

:私は、テーブルはこのように旋回する必要があります。これで

>>> df.pivot(index='id', columns='type') 

      quantity cost    
type   A B  A  B 
id        
1700057817 2 1  2383 744 

問題: - id組み合わせ

I

  1. dateインデックスが
  2. は私が dateごとに行が必要なくなってこれは私が得ているほど近いですまた、 this oneを含むSOやその他の記事をいくつか読んできました。

答えて

2

あなたはappend=Trueと​​がunstackが続くとMultiIndexを保つことができる:

df.set_index(['id', 'type'], append=True).unstack() 

enter image description here

あるいは強制的にあなたが求めているものに再フォーマット:

# step-one same as above 
df1 = df.set_index(['id', 'type'], append=True).unstack() 
# collapse MultiIndex columns into '-' separated string 
df1.columns = df1.columns.swaplevel(0, 1).to_series().str.join('-') 
# move 'Id' from the index back into dataframe proper 
df1 = df1.reset_index(1) 
df1 

enter image description here

1

reset_indexを使用して日付を保存できます。

df.index.name = 'date' 
df = df.reset_index().pivot_table(index=['date', 'id'], columns=['type']) 
df = df.sort_index(axis=1, level=1) 
df.columns = ['-'.join(tup[::-1]) for tup in df.columns] 
+0

バグだと分かっていませんが、pivot_tableは数値以外の列を捨ててしまっているようです。したがって、文字列の列 'customer'を追加すると、これは破棄されます。 – jf328

+0

ああ、pivot_tableはあなたの値が長さ1であっても集計しようとします。だから 'pivot_table(index、columns、aggfunc = lambda x:x.values [0])'は文字列を取得します。 – jf328

関連する問題