【问题标题】:How to check if any row is more than x and return name of column?如何检查任何行是否超过 x 并返回列名?
【发布时间】:2021-07-07 09:42:45
【问题描述】:

我有 id、col1、col2、col3、col4 的数据框,如图片中所述。

我想编写一个函数来查找是否有任何行大于 x 的列的返回名称,其中该条件为真,并将其返回到结果列中。

userid  col1    col2    col3    col4    result
d1  40  50  75  65  col3
d2  54  20  61  71  col4
d3  12  75  12  60  col2
d4  75  12  14  16  col1

【问题讨论】:

  • 如果多列将包含值怎么办> x 你期望什么?

标签: python pandas


【解决方案1】:

您可以使用idxmax(axis=1) 来处理列:

>>> df[['col1','col2','col3','col4']].idxmax(axis=1)
0    col3
1    col4
2    col2
3    col1
dtype: object

并将其分配给您的df

>>> df['result'] = df[['col1','col2','col3','col4']].idxmax(axis=1)

你得到:

>>> df
    userid  col1    col2    col3    col4    result
0   d1        40      50      75      65      col3
1   d2        54      20      61      71      col4
2   d3        12      75      12      60      col2
3   d4        75      12      14      16      col1

【讨论】:

  • 嗨@Jcole2020,如果这个或任何答案解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
【解决方案2】:

您可以使用.select_dtypes() 过滤这些带有数字的列,然后将这些列与x 进行比较,并通过.idxmax(axis=1) 跨行获取列名称,如下所示:

(假设下面是x = 70):

x = 70           
df2 = df.select_dtypes('number')
df['result'] = (df2 > x).idxmax(axis=1)

结果:

print(df)

  userid  col1  col2  col3  col4 result
0     d1    40    50    75    65   col3
1     d2    54    20    61    71   col4
2     d3    12    75    12    60   col2
3     d4    75    12    14    16   col1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 2010-09-17
    相关资源
    最近更新 更多