【发布时间】:2017-01-26 10:32:53
【问题描述】:
我有一个 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
这是我从 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
【问题讨论】:
-
可以分享你的
xls吗? -
刚刚在问题末尾添加了截图
-
ZAF的值在哪里?仅在COU列中? -
是的,仅在 COU 列中
-
我认为问题出在
data_CO2PROD。data_CO2PROD.info()是什么?我认为列中有Multiindex。
标签: python pandas matplotlib panel-data