2016-09-20 67 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