我有三个数据,需要根据给出的指令进行合并。
第一个数据是'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'的GDP数据,这是一个csv,包含从1960年到2015年World Bank的国家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年(2006-2015)的GDP数据,仅使用Scimagojr'Rank'排名前15个国家(等级1到15)。
此DataFrame的索引应为国家/地区的名称,列应为:
['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)
所以,关注的是,虽然它有效,但我需要为更大的未来数据集找到更有效的方法。有没有办法做到这一点?
感谢。
答案 0 :(得分:0)
以下是在一行代码中进行三向合并的方法:
df1 = data1.set_index('country')
df2 = data2.set_index('country')
df3 = data3.set_index('country')
new_df = pd.concat([df1, df2, df3], axis=1)