开发者社区 问答 正文

如何在dataframe中获取某个值的列名

我有一张这样的桌子

uid|store_1_@_A|store_2_%_7_B|store_3_&_9_C
---------------------------------------
1  |3          |4            |5
2  |20         |1            |9
3  |4          |88           |49    

我想形成一个新的表这样:

uid|store_1_@_A|store_2_%_7_B|store_3_&_9_C|favorite_store
------------------------------------------------------
1  |3          |4            |5            |C
2  |20         |1            |9            |A
3  |4          |88           |49           |B

favorite_store是一个新变量。对于每个uid,检查三个存储的值,并找到值最高的一个,即e。g: uid =1,最大值= 5,属于store_3_&_9_C,所以favorite_store = C。

df = pd.DataFrame({'uid':[1,2,3],
                   'store_1_@_A':[3,20,4],
                   'store_2_%_7_B':[4,1,88],
                   'store_3_&_9_C':[5,9,49]})

我使用df.iloc[0].max()来获得第一行的最大值,但是我不知道如何继续。 如果在商店的名字中得到最后一个字符,我在考虑使用最后一个'_'。如re.findall (“[^ \ _] + $”,“re.findall (“[^ \ _] + $”,“store_3_A”)[0]”)[0]可能工作。 问题来源StackOverflow 地址:/questions/59385970/how-to-get-a-certain-values-column-name-in-a-dataframe

展开
收起
kun坤 2019-12-25 22:11:05 1441 分享 版权
1 条回答
写回答
取消 提交回答
  • 试试这个:

    df['favorite_store'] = df.T.idxmax()                                                                                                                                                
    
    In [5248]: df                                                                                                                                                                                  
    Out[5248]: 
       uid  store_1  store_2  store_3 favorite_store
    0    1        3        4        5        store_3
    1    2       20        1        9        store_1
    2    3        4       88       49        store_2
    
    or
    
    df['favorite_store'] = df.T.idxmax().str.extract(r'store_(\d+)')                                                                                                                    
    
    In [5266]: df                                                                                                                                                                                  
    Out[5266]: 
       uid  store_1  store_2  store_3 favorite_store
    0    1        3        4        5              3
    1    2       20        1        9              1
    2    3        4       88       49              2
    
    
    2019-12-25 22:11:16
    赞同 展开评论
问答分类:
问答地址: