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.
Actrully中,'i'循環用於命名系列。 'site.index'是一個名字列表。我認爲它不能使用'如果我=='生成'df' – Cobin
@Cobin啊,我的道歉。我編輯了我的答案,使用enumerate()來跟蹤使用計數器「iter」的迭代,同時保留i作爲站點名稱。 –
Thx非常!我會試試看。這個解決方案在我的數據操作中很有用。 – Cobin