我在資料框中有幾列具有綠色/黃色/紅色值:
樣本:
| 日期 | 索引1 | 索引2 |
|---|---|---|
| 21 年 12 月 20 日 | 綠 | 黃色的 |
| 21 年 12 月 21 日 | 紅色的 | 黃色的 |
我想在這個資料框中再添加一列,它首先根據邏輯為每列分配一個分數:如果綠色,分數 = 1,如果黃色,則為 0.5,如果紅色,則為 0,然后將這些單獨的分數相加以產生最終分數。例如。對于第 1 行,得分 = 1 0.5 = 1.5,對于第 2 行得分 = 0 0.5 =0.5,依此類推。
func 本身很容易撰寫:
def color_to_score(x):
if (x=='Green'):
return 1
elif (x=='Yellow'):
return 0.5
else: return 0
但是我正在努力將其應用于每一列,然后跨列添加結果分數以優雅的方式生成一個新分數。我顯然可以做這樣的事情:
df['Index1score'] = df['Index1'].apply(color_to_score)
為每個相關列生成一個分數列,然后添加它們,但這非常不優雅且不可擴展。尋求幫助。
uj5u.com熱心網友回復:
這是使用的替代方法replace():
replace_dict = {'Green':1,'Yellow':.5,'\w':0}
df.assign(new_col = df[['col1','col2']].replace(replace_dict,regex=True).sum(axis=1))
此外,\w您可以使用pd.to_numeric()并設定errors = 'coerce'將所有非數字值轉換為NaN
replace_dict = {'Green':1,'Yellow':.5}
df.assign(new_col = pd.to_numeric(df[['col1','col2']].replace(replace_dict).stack(),errors='coerce').unstack().sum(axis=1))
輸出:
Date col1 col2 new_col
0 20-Dec-21 Green Yellow 1.5
1 21-Dec-21 Red Yellow 0.5
uj5u.com熱心網友回復:
- 您需要提供 Axis=1 以將該函式應用于每一行。2.
x在您的函式中將是一行(不是單元格)。 - 您可以將
x行轉換為串列。 - 計算每個值在串列中出現的次數,然后乘以它的值。
- 求和,輸出結果。
uj5u.com熱心網友回復:
選擇 Python 而不是 Pandas,讓您的生活更輕松。
score_dict = {'Green': 1, 'Yellow': 0.5, 'Red': 0}
df = pd.DataFrame(data)
df["total_score"] = 0.0
for index, row in df.iterrows():
df.at[index, "total_score"] = score_dict[row["Index1"]] score_dict[row["Index2"]]
print(df)
uj5u.com熱心網友回復:
想出了這個解決方案。
scores = []
for index in range(len(df.index)):
scoreTotal = 0
for column in df.columns:
color = df[column][index]
scoreTotal = color_to_score(color)
scores.append(scoreTotal)
df["Score"] = scores
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/397674.html
