【问题标题】:Pandas max value indexPandas 最大值指数
【发布时间】:2017-02-19 05:54:14
【问题描述】:

我有一个 Pandas DataFrame,其中包含屏幕名称、推文、收藏夹等。我想找到“favcount”的最大值(我已经完成了)并返回该“推文”的屏幕名称

df = pd.DataFrame()
df['timestamp'] = timestamp
df['sn'] = sn
df['text'] = text
df['favcount'] = fav_count


print df
print '------'
print df['favcount'].max()

我似乎在这方面找不到任何东西,谁能帮助指导我正确的方向?

【问题讨论】:

    标签: python pandas twitter indexing max


    【解决方案1】:

    使用argmax() idxmax()获取最大值的索引。然后你可以使用loc

    df.loc[df['favcount'].idxmax(), 'sn']
    

    编辑: argmax() 现已弃用,改用 idxmax()

    【讨论】:

    • 如果你的列只包含 nan 值,这将导致 TypeError
    【解决方案2】:

    我认为您需要idxmax - 获取favcount 的最大值索引,然后通过locsn 列中选择值:

    df = pd.DataFrame({'favcount':[1,2,3], 'sn':['a','b','c']})
    
    print (df)
       favcount sn
    0         1  a
    1         2  b
    2         3  c
    
    print (df.favcount.idxmax())
    2
    
    print (df.loc[df.favcount.idxmax()])
    favcount    3
    sn          c
    Name: 2, dtype: object
    
    print (df.loc[df.favcount.idxmax(), 'sn'])
    c
    

    【讨论】:

      【解决方案3】:

      通过使用与上面相同的 df,

      #python代码
      

      df = pd.DataFrame({'favcount':[1,2,3], 'sn':['a','b','c']})

      打印 (df) 最喜欢的sn 0 1个 1 2 乙 2 3 c

      ## 你可以使用 max() 打印(df[df.favcount.max() == df['favcount']])

      favcount sn 2 3 c

      ##如果你需要特定的列,你可以选择它 打印(df[df.favcount.max() == df['favcount']].sn)

      2c

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-03
        • 2019-08-16
        • 1970-01-01
        • 2015-05-25
        • 2021-07-09
        • 2021-08-01
        相关资源
        最近更新 更多