我想添加一列以指示在每一行中哪個“分數”排名第 1 和第 2 的資料框。

import pandas as pd
from io import StringIO
csvfile = StringIO(
"""Name Department A_score B_score C_score D_score
Jason Finance 7 3 7 9
Jason Sales 2 2 9 2
Molly Operation 3 7 1 2
""")
df = pd.read_csv(csvfile, sep = '\t', engine='python')
# adding columns to indicate the ranks of A,B,C,D
df = df.join(df.rank(axis=1, ascending=False).astype(int).add_suffix('_rank'))
# returning the column headers that in [1, 2]
df_1 = df.apply(lambda x: x.isin([1,2]), axis=1).apply(lambda x: list(df.columns[x]), axis=1)
print (df_1)
# output as:
[A_score_rank, C_score_rank, D_score_rank]
[A_score, B_score, D_score, C_score_rank]
[C_score, D_score, A_score_rank, B_score_rank]
有兩個問題
- 檢查哪些是第一和第二名時,它包括“分數”列但是我只想按“排名”列運行它們
- df_1 作為單獨的資料幀出現,而不是擴展原始資料幀的一部分
我該如何解決這些?任何幫助我們的贊賞。謝謝你。
uj5u.com熱心網友回復:
我們可以這樣做,然后pd.Series.nlargest拉出 Not NaNone by列得到結果notnadot
s = df.filter(like='score').apply(pd.Series.nlargest,n=2,keep='all',axis=1)
df['new'] = s.notna().dot(s.columns ',').str[:-1]
df
Name Department A_score ... C_score D_score new
0 Jason Finance 7 ... 7 9 A_score,C_score,D_score
1 Jason Sales 3 ... 9 2 A_score,C_score
2 Molly Operation 3 ... 1 2 A_score,B_score
[3 rows x 7 columns]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/415725.html
標籤:
