[英]How to check if any row is more than x and return name of column?
我有 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
您可以将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
您可以使用.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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.