1、將批量下載好的原始數據保存在data文件夾,數據如圖:,總共有196101-201612長達56年的長時間序列數據。
2、需要將原始的數據按照索引數據進行批量處理好可用的月降水數據。具體代碼如下:
3、運行結果列表如圖:
python對地理數據的處理非常實用,有強大的數據分析工具包。不過具體的實現代碼需要有一定的python編程知識,本文代碼的撰寫來自代碼開頭聲明的作者,轉載需要注明該作者的版權。其中涉及到python對excel數據的讀取和存儲的應用,主要學習網址如下:https://pandas.pydata.org/pandas-docs/version/0.23/?tdsourcetag=s_pctim_aiomsg 。該實驗操作具體代碼如下:
1 import os,sys 2 import numpy as np 3 import pandas as pd 4 import csv 5 def txt_to_array(values): 6 return np.array([[i for i in filter(None,data[0].split(' '))] for data in values]) 7 8 def csv_write(path,data,index_array): 9 df=open(path,'w',newline='') 10 csv_writer=csv.writer(df) 11 header=['id','row','col','x','y','values'] 12 csv_writer.writerow(header) 13 for item in index_array: 14 item[-1]=data[int(item[1]),int(item[2])] 15 csv_writer.writerow(item) 16 df.close() 17 18 19 20 if __name__=="__main__": 21 22 # 研究區域位置索引文件,用arcgis處理得到,如果該文件和該運行文件在同一目錄,可以直接用文件名 23 #index_filename=r'index.txt' 24 index_filename=r'E:\rainfull\index.txt' #某地理位置區域的地理索引數據 25 #降雨數據所在的--目錄(dir) 26 rainfull_dir=r'E:\rainfull\data'#批量下載好的氣象數據網中的插值站點數據 27 #處理結果存放目錄 28 out_path=r'E:\rainfull\TRHrainfull40' 29 #最后的數據格式文件 30 out_file=r'E:\rainfull\TRHrainfull40\datahebing.txt'#將處理得到的每年的所有站點數據合並的文件 31 32 33 if os.path.exists(out_path)==False: 34 os.makedirs(out_path) 35 index_array=pd.read_csv(index_filename,header=0) 36 columns=index_array.columns.tolist() 37 row_index=columns.index('row') 38 index_array=index_array.values[:,(row_index-1):] 39 files=os.listdir(rainfull_dir) 40 for rainfull_filename in files: 41 (filename,extension)=os.path.splitext(rainfull_filename) 42 if extension=='.txt': 43 print(filename) 44 rainfull_path=os.path.join(rainfull_dir,rainfull_filename) 45 rainfull_array=pd.read_csv(rainfull_path,header=list(range(6))) 46 rainfull_array=rainfull_array.values 47 rainfull_array=txt_to_array(rainfull_array) 48 csv_write(os.path.join(out_path,filename+'.csv'),rainfull_array,index_array) 49 csv_file_list=os.listdir(out_path) 50 year_dict={} 51 site_count=0 52 for file in csv_file_list: 53 (filename,extension)=os.path.splitext(file) 54 if extension=='.csv': 55 year_mouth=filename.split('-')[-1] 56 file_path=os.path.join(out_path,file) 57 data=pd.read_csv(file_path,header=0) 58 data=data.values 59 data=data[:,-1].T 60 site_count=len(data) 61 year_dict[year_mouth]=data 62 with open(out_file,'w') as df: 63 df.write('Year,Mouth,') 64 for i in range(site_count): 65 df.write("site_"+str(i)) 66 df.write('\n') 67 68 for key,value in year_dict.items(): 69 year=key[0:4] 70 mouth=key[4:] 71 df.write(year+","+mouth+",") 72 value=','.join([str(i) for i in value.tolist()]) 73 df.write(value) 74 df.write('\n')