在pandas中使用from_records时出现断言错误

时间:2018-03-10 20:21:12

标签: pandas

我正在尝试为aruba加载gdp数据,如下所示:

block

我一直在LABELS = ["Country Name","1995","1996","1997","1998","1999","2000","2001","2002","2003","2004","2005","2006","2007","2008","2009"] RATES = ["Aruba","1.24508591166203","7.81443171889218","6.66662183020206","1.15446939174406","4.51406203251221","-0.364695778713454","-2.16445940890385","0.465289865491144","7.51947237328494","1.17669048367502","0.380390971382511","2.35511944298051","-3.65462624193272","-6.88130206359888","-5.65350208612952"] df = pd.DataFrame.from_records(data=RATES, columns=LABELS) #print(df.head()) print(len(LABELS)) print(len(RATES)) 。 但是LABELS和RATES的长度是一样的,16。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

你需要:

df = pd.DataFrame.from_records(data=[RATES], columns=LABELS)

这样做的原因是此方法假定您正在获得一个可迭代列表。字符串是可迭代的,因此它假定每个字符都应该是一个值。通过说[RATES],你清楚地表明列表应该只是一行。

df = pd.DataFrame.from_records(data=RATES)
print(df)
   0  1  2  3  4     5     6     7     8     9     10    11    12    13    14  \
0   A  r  u  b  a  None  None  None  None  None  None  None  None  None  None   
1   1  .  2  4  5     0     8     5     9     1     1     6     6     2     0   
2   7  .  8  1  4     4     3     1     7     1     8     8     9     2     1   
3   6  .  6  6  6     6     2     1     8     3     0     2     0     2     0   
4   1  .  1  5  4     4     6     9     3     9     1     7     4     4     0   
5   4  .  5  1  4     0     6     2     0     3     2     5     1     2     2   
6   -  0  .  3  6     4     6     9     5     7     7     8     7     1     3   
7   -  2  .  1  6     4     4     5     9     4     0     8     9     0     3   
8   0  .  4  6  5     2     8     9     8     6     5     4     9     1     1   
9   7  .  5  1  9     4     7     2     3     7     3     2     8     4     9   
10  1  .  1  7  6     6     9     0     4     8     3     6     7     5     0   
11  0  .  3  8  0     3     9     0     9     7     1     3     8     2     5   
12  2  .  3  5  5     1     1     9     4     4     2     9     8     0     5   
13  -  3  .  6  5     4     6     2     6     2     4     1     9     3     2   
14  -  6  .  8  8     1     3     0     2     0     6     3     5     9     8   
15  -  5  .  6  5     3     5     0     2     0     8     6     1     2     9   

      15    16    17  
0   None  None  None  
1      3  None  None  
2      8  None  None  
3      6  None  None  
4      6  None  None  
5      1  None  None  
6      4     5     4  
7      8     5  None  
8      4     4  None  
9      4  None  None  
10     2  None  None  
11     1     1  None  
12     1  None  None  
13     7     2  None  
14     8     8  None  
15     5     2  None