[英]How to add new column in pandas dataframe based on values in two other columns
[英]How do I add two new columns on the basis of the values of multiple other columns in a pandas dataframe?
我正在嘗試根據其他幾列的值將兩列添加到現有的 dataframe 中。 我的 dataframe 看起來像這樣:
df = pd.DataFrame({'Type':['A', 'A', 'A', 'B','',''], 'Type1':['A', 'A', '', 'B','',''], 'Type2':['A','B','B','B','A',''], 'Score':[1, 2, 3, 1, 0,0], 'Score1':[2, 1, 0, 1, 0,0], 'Score2':[1, 3, 2, 1, 2,0]})
Type Type1 Type2 Score Score1 Score2
0 A A A 1 2 1
1 A A B 2 1 3
2 A B 3 0 2
3 B B B 1 1 1
4 A 0 0 2
5 0 0 0
我想添加兩列“Score_A”和“Score_B”,這樣“Score_A”將是類型為“A”(每行)的情況下的得分平均值。 'Score_B' 也是如此。 一個問題是,只要 Type 為空白,則不應使用分數來計算平均值。
在這種情況下,成功的 function 的結果將是:
Score_A Score_B
1.33 0
1.5 3
3 2
0 1
2 0
0 0
我已經在行級別運行嵌套循環來執行此操作,但是有更好的方法嗎?
m1 = (df[['Type', 'Type1', 'Type2']] == 'A')
m2 = (df[['Type', 'Type1', 'Type2']] == 'B')
scores = df[['Score', 'Score1', 'Score2']]
df['Score_A'] = pd.DataFrame(np.where(m1, scores, np.nan)).mean(skipna=True, axis=1).fillna(0)
df['Score_B'] = pd.DataFrame(np.where(m2, scores, np.nan)).mean(skipna=True, axis=1).fillna(0)
print(df)
印刷:
Type Type1 Type2 Score Score1 Score2 Score_A Score_B
0 A A A 1 2 1 1.333333 0.0
1 A A B 2 1 3 1.500000 3.0
2 A B 3 0 2 3.000000 2.0
3 B B B 1 1 1 0.000000 1.0
4 A 0 0 2 2.000000 0.0
5 0 0 0 0.000000 0.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.