我有一個 dataframe1 顯示觀眾的評分和每部電影的型別:
movie_id| rating | action | comedy | drama
0 4 1 1 1
1 5 0 1 0
2 3 0 1 1
1 表示動作片表示這是一部動作片,0 表示不是。
我提取了單一型別的平均評分。舉個例子,我是這樣做的:
new=df1[df1["action"]==1]
new['rating'].mean()
其中顯示為 4。但現在我必須提取所有型別的平均評分,應該如下所示:
action | comedy | drama
4 4 3.5
關于如何接近的任何建議?
uj5u.com熱心網友回復:
在您的情況下,我們可以選擇列,然后選擇where所有 0 到NaN并mul帶有評級
out = df.loc[:,['action','comedy','drama']].where(lambda x : x==1).mul(df.rating,axis=0).mean()
Out[377]:
action 4.0
comedy 4.0
drama 3.5
dtype: float64
如果你想要一個資料框
out = out.to_frame().T
uj5u.com熱心網友回復:
您可以融合流派列并過濾以僅保持值等于 1。然后按流派分組并計算平均值。
pd.melt(
df,
value_vars=["action", "comedy", "drama"],
var_name="genre",
id_vars=["movie_id", "rating"],
).query("value == 1").groupby("genre")["rating"].mean()
這使
genre
action 4.0
comedy 4.0
drama 3.5
Name: rating, dtype: float64
uj5u.com熱心網友回復:
將rating列與action,comedy和drama列相乘,將 0 替換為 np.nan,然后計算平均值:
(df.iloc[:, 2:]
.mul(df.rating, axis = 0)
# mean implicitly excludes nulls during computations
.replace(0, np.nan)
.mean()
)
action 4.0
comedy 4.0
drama 3.5
dtype: float64
上面回傳一個系列,如果你想要一個像輸出這樣的資料幀,傳遞mean給 agg:
(df.iloc[:, 2:]
.mul(df.rating, axis = 0)
.replace(0, np.nan)
.agg(['mean']) # note the `mean` is in a list
)
action comedy drama
mean 4.0 4.0 3.5
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369047.html
