gpt4 book ai didi

python - 行的 Pandas 最大值,前 n 最大值

转载 作者:行者123 更新时间:2023-12-04 04:16:42 29 4
gpt4 key购买 nike

我正在尝试创建顶部列,这是几个列行的最大值。 Pandas 有一个方法 nlargest但我无法让它成行工作。 Pandas 也有 maxidxmax这正是我想做的,但仅限于绝对最大值。

df = pd.DataFrame(np.array([[1, 2, 3, 5, 1, 9], [4, 5, 6, 2, 5, 9], [7, 8, 9, 2, 5, 10]]), columns=['a', 'b', 'c', 'd', 'e', 'f'])
cols = df.columns[:-1].tolist()

df['max_1_val'] = df[cols].max(axis=1)
df['max_1_col'] = df[cols].idxmax(axis=1)

输出:

    a   b   c   d   e   f   max_1_val   max_1_col
0 1 2 3 5 1 9 5 d
1 4 5 6 2 5 9 6 c
2 7 8 9 2 5 10 9 c

但我正在尝试获取 max_n_val 和 max_n_col,因此前 3 名的预期输出为:

    a   b   c   d   e   f   max_1_val   max_1_col   max_2_val   max_2_col   max_3_val   max_3_col
0 1 2 3 5 1 9 5 d 3 c 2 b
1 4 5 6 2 5 9 6 c 5 b 5 e
2 7 8 9 2 5 10 9 c 8 b 7 a

最佳答案

为了提高性能,使用了 numpy.argsort对于位置,为了正确顺序使用最后 3 个项目,通过索引反转:

N = 3
a = df[cols].to_numpy().argsort()[:, :-N-1:-1]
print (a)
[[3 2 1]
[2 4 1]
[2 1 0]]

然后通过索引到 c 获取列名,并在 d 中重新排序值使用 this解决方案:

c = np.array(cols)[a]
d = df[cols].to_numpy()[np.arange(a.shape[0])[:, None], a]

最后创建 DataFrame,通过 concat 加入并按 DataFrame.reindex 对列名称重新排序:

df1 = pd.DataFrame(c).rename(columns=lambda x : f'max_{x+1}_col')
df2 = pd.DataFrame(d).rename(columns=lambda x : f'max_{x+1}_val')

c = df.columns.tolist() + [y for x in zip(df2.columns, df1.columns) for y in x]

df = pd.concat([df, df1, df2], axis=1).reindex(c, axis=1)
print (df)
a b c d e f max_1_val max_1_col max_2_val max_2_col max_3_val \
0 1 2 3 5 1 9 5 d 3 c 2
1 4 5 6 2 5 9 6 c 5 e 5
2 7 8 9 2 5 10 9 c 8 b 7

max_3_col
0 b
1 b
2 a

关于python - 行的 Pandas 最大值,前 n 最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60633090/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com