Python,策划熊猫'来自长数据的pivot_table

时间:2016-09-18 18:35:40

标签: python pandas matplotlib panel-data

我有一个xls文件,数据以长格式组织。我有四列:变量名称,国家/地区名称,年份和值。

使用pandas.read_excel在Python中导入数据后,我想绘制一个变量的时间序列,用于不同的国家/地区。为此,我创建了一个数据透视表,以宽格式转换数据。当我尝试用matplotlib绘图时,我收到错误

ValueError: could not convert string to float: 'ZAF'

(其中' ZAF'是一个国家/地区的标签)

问题是什么?

这是代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_excel('raw_emissions_energy.xls','raw data', index_col = None, thousands='.',parse_cols="A,C,F,M")

data['Year'] = data['Year'].astype(str)
data['COU'] = data['COU'].astype(str)

# generate sub-datasets for specific VARs

data_CO2PROD = pd.pivot_table(data[(data['VAR']=='CO2_PBPROD')], index='COU', columns='Year')

plt.plot(data_CO2PROD)

包含原始数据的xls文件如下所示: raw data Excel view

enter image description here

这是我从data_CO2PROD.info()

获得的
<class 'pandas.core.frame.DataFrame'>
Index: 105 entries, ARE to ZAF
Data columns (total 16 columns):
(Value, 1990)    104 non-null float64
(Value, 1995)    105 non-null float64
(Value, 2000)    105 non-null float64
(Value, 2001)    105 non-null float64
(Value, 2002)    105 non-null float64
(Value, 2003)    105 non-null float64
(Value, 2004)    105 non-null float64
(Value, 2005)    105 non-null float64
(Value, 2006)    105 non-null float64
(Value, 2007)    105 non-null float64
(Value, 2008)    105 non-null float64
(Value, 2009)    105 non-null float64
(Value, 2010)    105 non-null float64
(Value, 2011)    105 non-null float64
(Value, 2012)    105 non-null float64
(Value, 2013)    105 non-null float64
dtypes: float64(16)
memory usage: 13.9+ KB
None

2 个答案:

答案 0 :(得分:1)

使用data_CO2PROD.plot()而不是plt.plot(data_CO2PROD)允许我绘制数据。 http://pandas.pydata.org/pandas-docs/stable/visualization.html。 简单的代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data= pd.DataFrame(np.random.randn(3,4), columns=['VAR','COU','Year','VAL'])
data['VAR'] = ['CC','CC','KK']
data['COU'] =['ZAF','NL','DK']
data['Year']=['1987','1987','2006']
data['VAL'] = [32,33,35]

data['Year'] = data['Year'].astype(str)
data['COU'] = data['COU'].astype(str)

# generate sub-datasets for specific VARs

data_CO2PROD = pd.pivot_table(data=data[(data['VAR']=='CC')], index='COU',    columns='Year')
data_CO2PROD.plot()
plt.show()

答案 1 :(得分:0)

我认为您需要将参数values添加到pivot_table

data_CO2PROD = pd.pivot_table(data=data[(data['VAR']=='CC')], 
                              index='COU', 
                              columns='Year', 
                              values='Value')

data_CO2PROD.plot()
plt.show()