Q:

How to find a value in columns and return the column name in Python

I have the following pivot table, with the last column returning the max value of the row.
            totalCount                          max
hours           0   1   2   3   ... 21  22  23  
    username                                                                                    
    user_1      3   0   0   5   ... 0   0   1   5
    user_2      0   0   6   0   ... 2   4   0   6   
    user_3      5   0   0   3   ... 0   0   1   5
    user_4      0   2   3   0   ... 0   8   0   8
    user_5      1   4   0   0   ... 5   9   2   9

Now I want to add another column 'hour' that returns the name of the column where the max value belongs.
The output would be the following:
            totalCount                          max hour
hours           0   1   2   3   ... 21  22  23  
    username                                                                                    
    user_1      3   0   0   5   ... 0   0   1   5   3
    user_2      0   0   6   0   ... 2   4   0   6   2
    user_3      5   0   0   3   ... 0   0   1   5   0
    user_4      0   2   3   0   ... 0   8   0   8   22
    user_5      1   4   0   0   ... 5   9   2   9   22

Any idea on how to create this column that finds the column name?
And what if the max value is repeated in various columns? I guess I would be returned the name of the first column that has that value, but would be any code to get all the column names where this max value appears? (This is an extra question that I appreciate if you can answer, but the main question is the previous one).

A:

You can use .idxmax() which returns the index of the max element coupled with .apply on axis=1:
df['where_max'] = df.apply(lambda x: x.idxmax(), axis=1)

Minimal Example:
df = pd.DataFrame(data={'x': [1, 3, 4, 7], 'wave': [2, 2, 10, 0], 'y': [0,0,0,15]})
df['where_max'] = df.apply(lambda x : x.idxmax(), axis=1)

    x   wave    y   where_max
0   1   2       0   wave
1   3   2       0   x
2   4   10      0   wave
3   7   0       15  y

