I will provide the full code below, but the problem basically is this: I created a data structure like this: means = {ID1 : { HOUR1 : [AVERAGE_FLOW, NUMBER_OF_SAMPLES] ...}
I created AVERAGE_FLOW using np.mean(). I can do this:
print means['716353'][0][0] #OUT : 76.6818181818
but when I run the second code when I want to :
means[row['ID']][i][0]
I get: TypeError: 'numpy.float64' object is not iterable
Here are the codes, the first one is where I produce the means data, and the second where I am trying to create a list:
shunned=[]
means={} #{ #DAY: [mean, number of samples]}
hour={}
for i in range(24):
hour[i]=[]
for station in stations:
means[station]=copy.deepcopy(hour)
for station in d:
for hour in range(24):
temp=[]
for day in range(1,31):
if day in sb: #swtich between sa for all days and sb for business days
try: #no entry = no counting in the mean, list index out of range, the station has not hourly data to begin with
e = d[station][str(day)][hour][0]
if not e: # sometimes we have '' for flow which, should not be counted
next
else:
temp.append(int(e))
except IndexError:
if station not in shunned:
shunned.append([station,d[station]])
else:
next
temp=np.array(temp)
means[station][hour]=[np.mean(temp),len(temp)]
pprint.pprint(means)
print means['716353'][0][0] #OUT : 76.6818181818
headers=['ID' , 'Lat', 'Lng', 'Link ID']+range(24)
csv_list=[]
meta_f.seek(0)
i=0
for row in meta_read:
if i>100:
break
temp=[]
if row['ID'] in stations:
temp.append([row['ID'],row['Latitude'],row['Longitude'],' '])
for i in range(24):
temp.extend(means[row['ID']][i][0])
csv_list.append(temp)
i+=1
pprint.pprint(csv_list) #OUT:temp.extend(means[row['ID']][i][0]) TypeError: 'numpy.float64' object is not iterable
I tried str(np.means(temp)) in the first code thinking maybe it is because of numpy, but it actually gave me the first digit of my value! as if it is ITERATING through a string...could you please explain what is going on? thank you!
It looks like you're trying to extend a list with a scalar float variable. The argument to extend must be an iterable (i.e. not a float). From your first bit of code it looks like means[i][j][k] returns a float,
print means['716353'][0][0] #OUT : 76.6818181818
The problem is here,
temp.extend(means[row['ID']][i][0])
If you expect that means[i][j][k] will always be a single value and not a list you can use append instead of extend.
temp.append( means[row['ID']][i][0] )
An example to show the difference,
l = [i for i in range(10)]
l.extend( 99.0 )
TypeError: 'float' object is not iterable
this doesn't work b/c a float is not iterable
l.extend( [99.0] )
print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99.0]
this works b/c a list is iterable (even a one element list)
l.append( 101.0 )
print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99.0, 101.0]
append does work with a non-iterable (e.g. a float)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With