I have text file having two columns: 1) column 1 is in the format yyyy-mm-dd and 2) column 2 is precipitation.
Objective: to extract original value of precipitation from column 2 only for month April, May, june, July, and August (4,5,6,7,8).
Procedure: Used line.split to extract only mm from yyyy-mm-dd format from column-1.
Problem: I can successfully print k,v (month and precipitation) from dictionary items. However, when I am using a if statement to extract the specific month's precipitation value, I am getting blank array. I was wondering can I use .append to get precipitation in (1.8,2.1,3.3)
format.
Code:
file1 = open("test.txt","r")
Growing=[]
Intermediate=[]
Dormant=[]
for line in file1:
line2 = line.split()
WQ = line2[1]
month = line2[0].split("-")[1]
dct1={month:WQ}
for k,v in dct1.items():
if (k ==4 or k==5 or k==6 or k==7 or k==8):
Growing.append(dct1 [k])
print Growing
A more obvious structure would be a dictionary of lists:
data = collections.defaultdict()
and in the loop
data.setdefault( month,[]).append( WQ )
and then later you can access each month's data by key.
Perhaps an easier way would be to use numpy.loadtxt,
map = {'jan':1,'feb':2,'mar':3,'apr':4,'may':5} # and the rest
data = numpy.loadtxt("test.txt",dtype = dtype([('month','S4'),('WQ',float)]))
and then select
data[data['month']=='apr']['WQ']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.