[英]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.