2016-09-20 77 views
0

我有这样的国家的名单:通过字符串调用数据帧

country = ["Brazil", "Chile", "Colombia", "Mexico", "Panama", "Peru", "Venezuela"] 

我创建使用的名字从国家列表中的数据帧:

for c in country: 
    c = pd.read_excel(str(c + ".xls"), skiprows = 1) 
    c = pd.to_datetime(c.Date, infer_datetime_format=True) 
    c = c[["Date", "spreads"]] 

现在我想成为能够使用列日期作为关键字合并所有国家的数据框架。我们的想法是创建类似下面的循环:

df = Brazil #this is the first dataframe, which also corresponds to the first element of the list country. 

for i in range(len(country)-1): 
    df = df.merge(country[i+1], on = "Date", how = "inner") 
df.set_index("Date", inplace=True) 

我得到了错误ValueError: can not merge DataFrame with instance of type <class 'str'>。看来python没有调用名字在国家列表中的数据框。我怎样才能从国家名单中调用这些数据框?

谢谢师父!

回答

0

您的循环不会修改country列表的内容,因此country仍然是一个字符串列表。

考虑构建dataframes的一个新的列表,并遍历是:

country_dfs = [] 
for c in country: 
    df = pd.read_excel(c + ".xls", skiprows=1) 
    df = pd.to_datetime(df.Date, infer_datetime_format=True) 
    df = df[["Date", "spreads"]] 
    # add new dataframe to our list of dataframes 
    country_dfs.append(df) 

然后合并,

merged_df = country_dfs[0] 
for df in country_dfs[1:]: 
    merged_df = merged_df.merge(df, on='Date', how='inner') 
merged_df.set_index('Date', inplace=True) 
+0

感谢您的见解。我明白了,但不知何故,我无法看到merged_df。 – Guga