【问题标题】:Pandas to add a column to indicate the 1st and 2nd places, according to row valuesPandas根据行值添加一列表示第1和第2位
【发布时间】:2022-11-25 07:57:28
【问题描述】:

我想添加一列以指示在每一行中哪个“分数”排名第一和第二的数据框。

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]

有两个问题

  1. 检查第一名和第二名时,它包括“分数”列,但我只想按“排名”列运行它们
  2. df_1 作为单独的数据帧出现,不是扩展原始数据帧的一部分

    我该如何解决这些问题?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我们可以做pd.Series.nlargest,然后把notnadot的Not NaN列拉出来得到结果

    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]
    

    【讨论】:

    • 谢谢你!这是一个了不起的解决方案!
    • 你也愿意帮忙吗——如果我想排名第二和第三,而不是第一和第二呢?
    • @MarkK 然后你需要先屏蔽最大值,然后取最大的两个:-)
    • @MarkK s = df.filter(like='score').mask(lambda x : x==x.max()).apply(pd.Series.nlargest,n=2,keep='all',axis=1)
    • 再次感谢指导和帮助。你太棒了!
    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多