我有三个数据,需要根据给出的指令进行合并。需要提高Python和熊猫数据操作的效率
第一个数据是'Energy Indicators.xls',它是来自联合国2013年的indicators of energy supply and renewable electricity production列表,应该放入一个名为'energy'的DataFrame中。
在放入DataFrame之前,必须从数据文件中排除页脚和标题信息以及前两列,因为它们是不必要的。
列标签的其余部分应该被改变,如:
['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']
缺失数据应被反映为np.NaN值。
下列国家的名单必须被重命名:
“大韩民国”: “韩国”,
“美利坚合众国”: “美国”,
“英国大不列颠及北爱尔兰“:”英国“,
”中国香港特别行政区“:”香港“。
也有几个国家的名字中有数字和/或括号。他们也需要被删除。
这部分是如下完成的:
import pandas as pd
import numpy as np
energy = pd.read_excel('Energy Indicators.xls',skiprows=17,skip_footer=38
,parse_cols =[2,3,4,5])
energy.columns = ['Country', 'Energy Supply', 'Energy Supply per Capita'
,'% Renewable']
energy.set_index('Country',inplace=True)
energy.replace('...', np.nan,inplace=True)
energy.set_index(energy.index.str.replace('\s*\(.*?\)\s*','')
.str.replace('\d+',''),inplace=True)
energy.rename(index={"Republic of Korea": "South Korea",
"United States of America": "United States",
"United Kingdom of Great Britain and Northern Ireland": "United Kingdom",
"China, Hong Kong Special Administrative Region": "Hong Kong"}
,inplace=True)
下一页数据是从该文件“world_bank.csv”,这是从World Bank含有国家从1960年到GDP 2015年一个csv GDP数据。
头必须被跳过,并重新命名下列国家的名单必须作如下更名为:“韩国,众议员”
:“韩国”,
“伊朗伊斯兰共和国”:“伊朗“,
”中国香港特别行政区“:”香港“。
该部分的代码在下面提供。
GDP=pd.read_csv('world_bank.csv',skiprows=4)
GDP.replace({'Country Name': {'Korea, Rep.': 'South Korea',
'Iran, Islamic Rep.': 'Iran',
'Hong Kong SAR, China': 'Hong Kong'}},inplace=True)
GDP.set_index('Country Name',inplace=True)
GDP.rename(index={'Country Name':'Country'},inplace=True)
最后的数据是'scimagojr-3.xlsx',它根据他们的期刊贡献对各国进行排名。 没有额外的工作,为他们操纵和代码如下写:
ScimEn=pd.read_excel('scimagojr-3.xlsx')
ScimEn.set_index('Country',inplace=True)
仅使用了近10年来GDP数据(2006- 2015年),只有加入使用国名的交叉点处的三个数据集Scimagojr'Rank'排名前15位的国家(排名1至15)。
该数据帧的指数应该是国家的名字,列应该是:
['Rank', 'Documents', 'Citable documents', 'Citations', 'Self-citations', 'Citations per document', 'H index', 'Energy Supply', 'Energy Supply per Capita', '% Renewable', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015']
。
这部分做如下:
df=pd.merge(ScimEn.iloc[0:15],
pd.merge(energy,GDP[['2006', '2007', '2008', '2009', '2010', '2011'
,'2012','2013','2014','2015']]
,left_index=True, right_index=True),left_index=True
,right_index=True)
因此,值得关注的是,虽然它的作品,我需要找到未来的大数据集的一个更有效的方法。有什么办法可以做到吗?
谢谢。
这是一个良好的书面问题,但太长了!跳到最后,看起来你只是问如何更有效地进行3-way合并,有可能也可能不是更好的方式 - 有时大数据的合并很慢,并且你可以做的不多。但是如果你想有一个很好的机会来接收有用的答案,你需要大大减少这个问题,把重点放在问题的核心上(这里只是一个三方合并,我可以用一眼就能看到) – JohnE