2017-05-29 8 views
1

を列の値を回す:はパンダのDFを旋回させる - 私はDFを持っている列名に

pd.DataFrame({'time_period': {0: pd.Timestamp('2017-04-01 00:00:00'), 
    1: pd.Timestamp('2017-04-01 00:00:00'), 
    2: pd.Timestamp('2017-03-01 00:00:00'), 
    3: pd.Timestamp('2017-03-01 00:00:00')}, 
'cost1': {0: 142.62999999999994, 
    1: 131.97000000000003, 
    2: 142.62999999999994, 
    3: 131.97000000000003}, 
'revenue1': {0: 56, 
    1: 113.14999999999998, 
    2: 177, 
    3: 99}, 
'cost2': {0: 309.85000000000002, 
    1: 258.25, 
    2: 309.85000000000002, 
    3: 258.25}, 
'revenue2': {0: 4.5, 
    1: 299.63,2: 309.85, 
    3: 258.25}, 
'City': {0: 'Boston', 
    1: 'New York',2: 'Boston', 
    3: 'New York'}}) 

を、私はこのような収益と費用のために別途ことdfを再構成したい:

pd.DataFrame({'City': {0: 'Boston', 1: 'New York'}, 
'Apr-17 revenue1': {0: 56.0, 1: 113.15000000000001}, 
'Apr-17 revenue2': {0: 4.5, 1: 299.63}, 
'Mar-17 revenue1': {0: 177, 1: 99}, 
'Mar-17 revenue2': {0: 309.85000000000002, 1: 258.25}}) 

と、A費用も同様です。

基本的には、それぞれ適切かつrevenue1/REVENUE2とcost1/cost2の値として売上/コスト文字列と4月-17、月-17のような列名にtime_period列の値をオンにします。

私はpd.pivot_tableでいくつかの成功を収めていますが、私が欲しいものを正確に得ることはできません。

+0

スタックを解除あなたの例を確認してください。予想される出力は入力DFのデータと一致しません(日付、Orlandoなどの収益)。 – Allen

+0

@Allen - それを指摘してくれてありがとう。私はちょうど修正した。 :-) – codingknob

+0

私は簡単に2番目の都市の列を削除しました..... – codingknob

答えて

2

使用set_indexと

import datetime as dt 
df['time_period'] = df['time_period'].apply(lambda x: dt.datetime.strftime(x,'%b-%Y')) 

df = df.set_index(['A', 'B', 'time_period'])[['revenue1', 'revenue2']].unstack().reset_index() 
df.columns = df.columns.map(' '.join) 


    A   B  revenue1 Apr-2017 revenue1 Mar-2017 revenue2 Apr-2017 revenue2 Mar-2017 
0 Boston  Orlando 56.00    177.0    4.50    309.85 
1 New York Dallas 113.15    99.0    299.63    258.25 
関連する問題