【问题标题】:Methods to Find Kth minimum number in pandas dataframe row在熊猫数据框行中查找第 K 个最小数的方法
【发布时间】:2020-08-30 09:24:55
【问题描述】:

给定一个包含 m 行和 n 列的数据框,我想要每行中的 minimum 列名。我正在使用 for 循环。接下来,我对获得的列进行测试,如果测试失败,我想要同一行中的第二个最小值,依此类推。

我当前的代码对每一行的数据框进行排序。当然,第一个值是最小值。我执行测试。如果测试失败,我会转到第二个值,依此类推。代码附在下面。 datadfObj 是 pandas 数据框对象。

for i in data.index:                                                #for each row
    dfObj = data.sort_values(by = i, axis=1, ascending = True)      #sorting by row and saving as new dataframe
    for column in dfObj:                                             # looping over column in sorted dataframe
         if some_condition true:
              perform action
          else:
              continue                                               # this takes me to next column

但是,这种方法非常缓慢且效率低下。这是对整个数据帧进行 m 次排序。如果可能的话,我想这样做而不进行排序。有没有更好的方法来做到这一点?

【问题讨论】:

  • 请提供输入和输出数据帧的示例。
  • 您对每行数据的实际执行情况是什么?

标签: python pandas performance dataframe series


【解决方案1】:

为了避免在每一行排序,您可以使用np.argsort 对其进行矢量化

#data
np.random.seed(0)
data = pd.DataFrame(np.random.randint(0,100, size=25).reshape(-1,5), 
                    columns=list('abcde'))

#your method
for i in data.index:
    dfObj = data.sort_values(by = i, axis=1, ascending = True)
    print (i, dfObj.columns)
# 0 Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
# 1 Index(['a', 'c', 'd', 'b', 'e'], dtype='object')
# 2 Index(['d', 'e', 'a', 'b', 'c'], dtype='object')
# 3 Index(['b', 'd', 'a', 'c', 'e'], dtype='object')
# 4 Index(['c', 'b', 'e', 'd', 'a'], dtype='object')

#vectorize way
print (data.columns.to_numpy()[np.argsort(data.to_numpy())])
# [['a' 'b' 'c' 'd' 'e']
#  ['a' 'c' 'd' 'b' 'e']
#  ['d' 'e' 'a' 'b' 'c']
#  ['b' 'd' 'a' 'c' 'e']
#  ['c' 'b' 'e' 'd' 'a']]

【讨论】:

    猜你喜欢
    • 2019-02-26
    • 2023-03-28
    • 2014-03-13
    • 1970-01-01
    • 2018-04-21
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多