gpt4 book ai didi

python - 对列进行排名并选择列名称

转载 作者:太空狗 更新时间:2023-10-30 01:28:05 26 4
gpt4 key购买 nike

如果我有 table :

a   b   c
15 15 5
20 10 7
25 30 9

并且想做两件事 1) 挑出横跨轴值最高的列并将其分配给一列 2) 取值并将其分配给另一列,例如:

a   b   c   1st 1st_value   2nd 2nd_value   3rd 3rd_value
15 15 5 a/b 15 c 5 NaN NaN
20 10 7 a 20 b 10 c 7
25 30 9 b 30 a 25 c 9

这可能吗?

最佳答案

我可以建议你这样解决:

import pandas as pd
import numpy as np

df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])
ext = {0: 'st', 1: 'nd', 2: 'rd'}
cols = df.columns


def make_ranking(row, rank=0, is_value=False):
values = list(row[cols])
sorted_values = sorted(set(values), reverse=True)
value = sorted_values[rank] if len(sorted_values) > rank else np.nan
if not is_value:
items = [k for k, v in enumerate(values) if v == value]
value = '/'.join([cols[item] for item in items]) or np.nan
return value

for i in range(len(cols)):
df[str(i+1)+ext[i]] = df.apply(make_ranking, args=(i, False, ), axis=1)
df[str(i+1)+ext[i]+'_value'] = df.apply(make_ranking, args=(i, True, ), axis=1)

print(df)

输出:

    a   b  c  1st  1st_value 2nd  2nd_value  3rd  3rd_value
0 15 15 5 a/b 15 c 5 NaN NaN
1 20 10 7 a 20 b 10 c 7
2 25 30 9 b 30 a 25 c 9

关于python - 对列进行排名并选择列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34961516/

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