2017-03-20 25 views
0

我生成了ts系列(包含索引和一列數據),然後在循環中逐個將一系列數據幀添加到df數據幀。但df是一個空的數據幀,它看起來像使用pd.concat是錯誤的。如何在循環時初始化df以與系列幀匹配?Pands:將循環生成的許多序列添加到數據幀

我的目的是將所有系列添加到數據框。請給我兩種方法:一種保留單個索引,其餘爲列數據,另一種保留每個序列包含一個索引和一個列數據。

sites = pd.read_excel(sitefile,index_col = 'site',header=0) 

for file in os.listdir(root): 
    ...... 

    df = pd.DataFrame()     # how to establish a df used to add new series data 
    for i in sites.index: 
     loni,lati = sites.loc[i,['lon','lat']] 
     dsloc = ds.sel(lon = loni,lat = lati,method = 'nearest') 

     #follow code main relate to this question 
     ts = pd.Series(dsloc[vname],index=dsloc['time'],name = i) # i in loop is a list of names ,used to name the sereis. 
     df = pd.concat([df,ts],axis=1,join_axes=[df.index]) 
    df.to_csv(csvfile) # the fist answer remind me that df.to_csv should jump out of the loop. 

回答

1

一個快速,簡單的方法是隻需添加一個條件,使你的第一個循環(i = 0)創建數據幀:

for file in os.listdir(root): 
    for iter, i in enumerate(sites.index): 
     loni,lati=sites.loc[i,['lon','lat']] 
     dsloc = ds.sel(lon=loni,lat=lati,method='nearest') 

     ts=pd.Series(dsloc[vname],index=dsloc['time'],name=i) 
     if iter==0: 
      # First iteration, create the DataFrame 
      df=pd.DataFrame(ts) 
     if iter>0: 
      # All other iterations, add to the DataFrame 
      df=pd.concat([df,ts],axis=1,join_axes=[df.index]) 
     df.to_csv(csvfile) 

我沒有你的數據的樣本所以我不確定代碼會運行。

另外,您寫的代碼會在每個循環中生成一個.csv文件。我不確定這是否是您的意圖,但只需生成一個最終csv,您應該將最後一行移至for循環之外。

+0

Actrully中,'i'循環用於命名系列。 'site.index'是一個名字列表。我認爲它不能使用'如果我=='生成'df' – Cobin

+0

@Cobin啊,我的道歉。我編輯了我的答案,使用enumerate()來跟蹤使用計數器「iter」的迭代,同時保留i作爲站點名稱。 –

+0

Thx非常!我會試試看。這個解決方案在我的數據操作中很有用。 – Cobin