For Loop确定加权平均python

Jes*_*sse 3 python for-loop dataframe pandas

我是Python的新手,我无法为一种情况制作正确的for循环.

我有一个dfclean包含两列的数据框:餐厅星级评分"Star_Rating"和评论总数"Review_Count".

我想找到这些星级评分的加权平均值(Star_Rating*(Review_Count /评论总数))并将它们添加到名为的新列中"weightedavg".

这是我到目前为止所记录的以及我认为我正在做的每一步的注意事项:

#get total number of reviews
totalreviews = dfclean.Review_Count.sum()

#create empty list to append values to
weightedavg = []

#for loop
for row in range(len(dfclean)):
    weightedavg.append(dfclean.Star_Rating[row] * (dfclean.Review_Count[row] / totalreviews))

#make a new column in df consisting of weightedavg
dfclean['weightedavg'] = weightedavg
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

Ale*_*lex 5

你不应该使用for循环.您可以利用广播来执行以下操作:

dfclean['weightedavg'] = dfclean['Star_Rating'] * dfclean['Review_Count'] / dfclean['Review_Count'].sum()
Run Code Online (Sandbox Code Playgroud)

这比使用Python循环要快得多,而且语法更清晰.您可以在numpy docspandas docs中阅读有关广播的内容.