Here I try to calculate mean value based on the data in two list of dict
s. Although I used same code before, I keep getting error. Is there any solution?
JavaScript
x
20
20
1
import pandas as pd
2
data = pd.read_csv('data3.csv',sep=';') # Reading data from csv
3
data = data.dropna(axis=0) # Drop rows with null values
4
data = data.T.to_dict().values() # Converting dataframe into list of dictionaries
5
newdata = pd.read_csv('newdata.csv',sep=';') # Reading data from csv
6
newdata = newdata.T.to_dict().values() # Converting dataframe into list of dictionaries
7
8
score = []
9
for item in newdata:
10
score.append({item['Genre_Name']:item['Ranking']})
11
12
13
from statistics import mean
14
score={k:int(v) for i in score for k,v in i.items()}
15
16
for item in data:
17
y= mean(map(score.get,map(str.strip,item['Recommended_Genres'].split(','))))
18
19
print(y)
20
Too see csv files: https://repl.it/@rmakakgn/SVE2
Advertisement
Answer
.get
method of dict
return None
if given key does not exist and statistics.mean
fail due to that, consider that
JavaScript
1
5
1
import statistics
2
d = {"a":1,"c":3}
3
data = [d.get(x) for x in ("a","b","c")]
4
print(statistics.mean(data))
5
result in:
JavaScript
1
2
1
TypeError: can't convert type 'NoneType' to numerator/denominator
2
You need to remove None
s before feeding into statistics.mean
, which you can do using list comprehension:
JavaScript
1
6
1
import statistics
2
d = {"a":1,"c":3}
3
data = [d.get(x) for x in ("a","b","c")]
4
data = [i for i in data if i is not None]
5
print(statistics.mean(data))
6
or filter
:
JavaScript
1
6
1
import statistics
2
d = {"a":1,"c":3}
3
data = [d.get(x) for x in ("a","b","c")]
4
data = filter(lambda x:x is not None,data)
5
print(statistics.mean(data))
6
(both snippets above code will print 2
)
In this particular case, you might get filter effect by replacing:
JavaScript
1
2
1
mean(map(score.get,map(str.strip,item['Recommended_Genres'].split(','))))
2
with:
JavaScript
1
2
1
mean([i for i in map(score.get,map(str.strip,item['Recommended_Genres'].split(','))) if i is not None])
2
though as with most python built-in and standard library functions accepting list as sole argument, you might decide to not build list but feed created generator directly i.e.
JavaScript
1
2
1
mean(i for i in map(score.get,map(str.strip,item['Recommended_Genres'].split(','))) if i is not None)
2