所以我需要浏览一个包含某些视频游戏信息的csv文件,并根据游戏的用户分数创建一个新变量,这是我的代码:
#Imports
import pandas
import numpy as np
import matplotlib.pyplot as plt
data = pandas.read_csv("Data Collections/metacritic_games_2016_11.csv", encoding='latin-1')
data['year'] = pandas.DatetimeIndex(data['release']).year
data = data[data["year"] >= 2000]
rating = []
for index, row in data.iterrows():
if row['user_score'] >= 7.5:
rating.append("Good")
elif row['user_score'] >= 6.5:
rating.append("Average")
elif row['user_score'] >= 0:
rating.append("Bad")
data["new_rating"] = pandas.Series(rating)
year = 2000
index = 0
while year != 2016:
vals = data[data["year"] == year]["new_rating"].value_counts()
plt.bar(index, vals["Bad"], color='#494953')
plt.bar(index, vals["Average"], color='#6A7EFC', bottom=vals["Bad"])
plt.bar(index, vals["Good"], color='#FF5656', bottom=vals["Average"] + vals["Bad"])
index += 1
year += 1
plt.show()
但是我一直收到错误说:
if row['user_score'] >= 7.5:
TypeError: '>=' not supported between instances of 'str' and 'float'
我不知道该怎么做。任何帮助表示赞赏
答案 0 :(得分:2)
由于某种原因,user_score
列中的某个数字被视为字符串。假设它不是"seventeen"
之类的值,您可以使用
data['user_score'] = data['user_score'].astype(float)
我还建议您更换用于创建rating
列的代码。而不是:
rating = []
for index, row in data.iterrows():
if row['user_score'] >= 7.5:
rating.append("Good")
elif row['user_score'] >= 6.5:
rating.append("Average")
elif row['user_score'] >= 0:
rating.append("Bad")
data["new_rating"] = pandas.Series(rating)
你应该这样做:
group_boundaries = [0, 6.5, 7.5, inf]
group_labels = ['bad', 'average', 'good']
data['rating'] = pd.cut(data['user_score'],
bins = group_boundaries,
labels=group_labels)