gpt4 book ai didi

python - 从 Python Dataframe 返回连续第六大值

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:28 25 4
gpt4 key购买 nike

我希望将 df 中 10 列的第 6 大行值返回到新列中,在本例中称为“6th_largest”。在整个 df 的许多情况下,可能有不止一行共享第 6 大值。不管是一个还是几个,我只需要返回实际的第6大值即可。

这里类似问题的几个选项没有用,因为它们通常特定于最大值(我已经能够做到)或仅第一个和第二个值。


import pandas as pd

#what the actual df might look like

data_actual = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9,10]]

df_actual=pd.DataFrame(data_actual, columns=['1st','2nd','3rd','4th','5th','6th',
'7th','8th','9th','10th'])

#what I want the df to look like after the calculation, returning the 6th largest value.

data_want = [[0, 1, 2, 3, 5, 5, 6, 7, 8, 9, 5], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5]]

df_want=pd.DataFrame(data_want, columns=['1st','2nd','3rd','4th','5th','6th',
'7th','8th','9th','10th', '6th Largest'])

最佳答案

使用、排名:

df_actual['6th Largest'] = df_actual.where(df_actual.rank(axis=1) == 6).dropna(axis=1)

输出:

   1st  2nd  3rd  4th  5th  6th  7th  8th  9th  10th  6th Largest
0 0 1 2 3 4 5 6 7 8 9 5
1 1 2 3 4 5 6 7 8 9 10 6

关于python - 从 Python Dataframe 返回连续第六大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58943299/

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