读取非结构化数据pandas

时间:2018-01-26 17:49:12

标签: python pandas

我在excel中有数据集,它没有出色的表格格式。以下是样本:

Country           Male                            Female
             2010  2011 2012 2013 2014        2010  2011 2012 2013 2014
 AFG         182   134   94  87   85           120   150   95  75   92
 BLZ         200    250  150  125 45           210    140  125 101  21

我想用Python读取这些数据并将其放入pandas数据框中,如:

Country    Year    Male  Female
AFG         2010   182    120
...

在没有操作原始数据集的情况下,Python / Pandas中是否有任何方法可以解决这个问题?

您可以在此处设置示例数据集:

https://expirebox.com/download/173bc0880dd9da56ccff2796aa1274ed.html

由于

1 个答案:

答案 0 :(得分:2)

解决方案 - 由pandas native excel reader选项提供。

在这里找到了这个技术: reading excel sheet as multiindex dataframe through pd.read_excel()

df = pd.read_excel('Sample.xlsx',header=[0,1],index_col=[0,1])

给出:

Country             Male                                    Female                                 
                    1990     2000    2010    2015    2016     1990     2000    2010    2015    2016
AFG Afghanistan 127.0000  96.5000 70.0000 58.7000 56.9000 113.2000  84.7000 61.2000 50.8000 49.2000
ALB Albania      38.1000  25.5000 16.4000 13.7000 13.3000  31.0000  20.6000 13.2000 11.1000 10.7000
DZA Algeria      45.0000  36.7000 24.9000 23.2000 22.9000  37.5000  31.1000 22.0000 20.5000 20.2000
AND Andorra       8.0000   4.3000  3.2000  2.7000  2.7000   6.6000   3.7000  2.7000  2.3000  2.3000
AGO Angola      140.6000 132.7000 82.4000 62.5000 60.0000 120.9000 112.8000 68.0000 51.0000 49.0000

并完成所需的布局使用stack()

df.stack()

Country                                       Female     Male
AFG Afghanistan                        1990 113.2000 127.0000
                                       2000  84.7000  96.5000
                                       2010  61.2000  70.0000
                                       2015  50.8000  58.7000