【问题标题】:Read unstructured data pandas读取非结构化数据 pandas
【发布时间】:2018-07-06 02:48:27
【问题描述】:

我在 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

谢谢

【问题讨论】:

  • 你能将 excel 文件加载到数据框中吗?
  • 您可能想要查看某种multiindex。您可以在 this question? 上找到帮助。这里的简短回答可能是:是的 - 这可以通过一些代码来完成。但如果它是一次性加载,它可能只是更快地处理原始数据集。如果它是一个恒定的负载,可能会花费一些时间来正确编写代码

标签: python pandas


【解决方案1】:

一种解决方案 - 由 pandas 原生 excel 阅读器选项提供。

在这里找到了技术: 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

【讨论】:

  • 这个答案比我的好多了:)
猜你喜欢
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-10
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多