从 Pivot 重塑和选择 Pandas
Reshaping & Selecting Pandas from Pivot
问题
我有以下数据框(注意值只是为了显示格式):
>>> print df
Country Public Private
Date
2013-01-17 BE 3389
2013-01-17 DK 4532 681
2013-02-21 DE 2453 1752
2013-02-21 IE 5143
2013-02-21 ES 8633 353
2013-03-21 FR 262
2013-03-21 LT 358
我想旋转它以显示以下格式:
Country Country1 Country2
Private Public Private Public
Date
2013-01-17 681 353 262 5143
2013-02-21 149 176 124 1757
2013-03-21 149 176 124 1757
产生问题
这会产生问题
import pandas as pd
data =[['2013-01-17', 'BE',1000,3389],
['2013-01-17', 'IE',5823, 681],
['2013-01-17', 'FR',1000,1752],
['2013-02-17', 'IE',1000,5143],
['2013-02-17', 'FR',1000, 353],
['2013-03-17', 'FR',1000, 262],
['2013-03-17', 'BE',1000, 358]]
df = pd.DataFrame(data,columns=['Date','Country','Public','Private']).set_index('Date')
尝试次数
我能做的最好的事情就是把国家和数据描述弄错:
>>> print df.pivot(index=df.index,columns='Country').fillna('')
Public Private
Country AT BE DE DK
Date
2013-01-17 1000 1000 1000 1000
2013-02-21 1000 1000 1000 1000
2013-03-21 1000 1000 1000 1000
您可以使用交换级别来交换它们。 http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.swaplevel.html
df.pivot(index=df.index,columns='Country').fillna('').swaplevel(0,1, axis=1).sortlevel(axis=1 )
问题
我有以下数据框(注意值只是为了显示格式):
>>> print df
Country Public Private
Date
2013-01-17 BE 3389
2013-01-17 DK 4532 681
2013-02-21 DE 2453 1752
2013-02-21 IE 5143
2013-02-21 ES 8633 353
2013-03-21 FR 262
2013-03-21 LT 358
我想旋转它以显示以下格式:
Country Country1 Country2
Private Public Private Public
Date
2013-01-17 681 353 262 5143
2013-02-21 149 176 124 1757
2013-03-21 149 176 124 1757
产生问题
这会产生问题
import pandas as pd
data =[['2013-01-17', 'BE',1000,3389],
['2013-01-17', 'IE',5823, 681],
['2013-01-17', 'FR',1000,1752],
['2013-02-17', 'IE',1000,5143],
['2013-02-17', 'FR',1000, 353],
['2013-03-17', 'FR',1000, 262],
['2013-03-17', 'BE',1000, 358]]
df = pd.DataFrame(data,columns=['Date','Country','Public','Private']).set_index('Date')
尝试次数
我能做的最好的事情就是把国家和数据描述弄错:
>>> print df.pivot(index=df.index,columns='Country').fillna('')
Public Private
Country AT BE DE DK
Date
2013-01-17 1000 1000 1000 1000
2013-02-21 1000 1000 1000 1000
2013-03-21 1000 1000 1000 1000
您可以使用交换级别来交换它们。 http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.swaplevel.html
df.pivot(index=df.index,columns='Country').fillna('').swaplevel(0,1, axis=1).sortlevel(axis=1 )