【问题标题】:Get the top N values from each row of a Pandas dataframe with their respective Column names从 Pandas 数据帧的每一行中获取前 N 个值及其各自的列名
【发布时间】:2020-11-23 17:13:47
【问题描述】:
Index          Class 1               Class 2         Class 3         Class 4          Class 5  
0              0.95693475            0.252198994      0.0            0.335894585      0.611441553
1              0.473615974           0.0              0.510585248    0.5007305        0.975620011
2              0.224682823           0.122315248      0.6407305        0.0            0.872211390

这是我正在处理的数据框的示例。我的原始数据框中大约有 200 Class's 和大约 85000 行,对于我的数据框的每一行,我想找出前 3 个类别,它们的值按降序排序:

    Expected output:
    Row 0: [{Class 1 : 95693475}, {Class 5: 0.611441553}, {Class 4: 0.335894585}]
    Row 1: [{Class 5 : 0.975620011}, {Class 3: 0.510585248}, {Class 4: 0.5007305}]
etc etc...

注意:预期输出中的List和dict只是添加参考,只需要输出数据框中每一行的前3个分数及其类别名称。谁能帮我解决这个问题

【问题讨论】:

  • 到目前为止你有什么尝试@Erich?

标签: python pandas dataframe sorting series


【解决方案1】:

参考资料:

Apply funtion to row in pandas - Example 3

Return first n keyvalue pairs from dict

从dict返回前n个键值对

from itertools import islice
def take(n, iterable):
    return list(islice(iterable, n))

删除索引列

df.drop('Index', axis=1,inplace=True)

可应用于所有行以查找前 3 个类别的函数

topN 函数将row 作为输入参数:这将是数据框的一行,n:表示要提取的最顶层元素的数量。

def topN(row, n):
    x = row.to_dict() # convert the input row to a dictionary 
    x = {k: v for k, v in sorted(x.items(), key=lambda item: -item[1])} # sort the dictionary based on their values 
    n_items = take(n, x.items()) # extract the first n values from the dictionary 
    return n_items
n = 3 #number of elements needed
df['X'] = df.apply(lambda row : topN(row,n), axis = 1) 

输出:

存储了一个新列X,其中包含作为字典的所需结果。您也可以将列转换为数组。

Class 1 Class 2 Class 3 Class 4 Class 5 X
0   0.956935    0.252199    0.000000    0.335895    0.611442    [(Class 1, 0.95693475), (Class 5 , 0.61144155...
1   0.473616    0.000000    0.510585    0.500731    0.975620    [(Class 5 , 0.975620011), (Class 3, 0.5105852...
2   0.224683    0.122315    0.640730    0.000000    0.872211    [(Class 5 , 0.87221139), (Class 3, 0.6407305)...

使用0.0 删除所有值的示例:

d = {1:0.0, 2:0.0, 3:1.0}
x={k:v for k,v in d.items() if v}
x # prints {3: 1.0}

【讨论】:

  • 谢谢。你能解释一下你的topN函数吗?同样连续,如果除值 1.0 之外的所有值均为 0.0,如何仅获得 1 个输入,即场景的 1.0 而不是 3 个输出
  • 感谢您的解释。我想了解您为什么在将 x 分配给已排序字典的行中执行 x.items 。同样在尝试用 0.0 过滤掉键时,我尝试了这段代码x = {k: v for k, v in sorted(x.items() if v != '0.0', key=lambda item: -item[1])},但它给了我一个语法错误
  • 知道如何解决这个问题吗?
  • 字典通常是不可迭代的,我们可以使用.items()来迭代它。并让您的代码更简单,删除排序行之前的0.0。
  • 不要更改字典排序的行。在此之前包括另一行:x={k:v for k,v in x.items() if v},您可以在其中仅包含字典中具有非零值的那些键。请参阅我答案底部的示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-20
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 2022-07-28
  • 2016-11-12
相关资源
最近更新 更多