【问题标题】:Python how to use idxmax() to get the full row values but based on a condition on a specific fieldPython 如何使用 idxmax() 获取完整的行值,但基于特定字段的条件
【发布时间】:2020-10-31 16:02:06
【问题描述】:

我需要获取数据框中特定区域的最高温度。只需应用以下内容:

df.loc[(df['Max Temperature'].idxmax())]

它正在工作,结果是:

Date                   2012-07-19 00:00:00

Precipitation [mm]                       0

Average Temperature                  28.28

Max Temperature                      39.42

MonthName                             July

Day                                     19

MonthNbr                                 7

Year                                  2012

Area                                Bekaa

AvgTest                              28.28

Name: 1176, dtype: object

我需要获取最大值的行,但针对特定区域。我尝试添加如下条件:

df.loc[df['Max Temperature']==df['Max Temperature'].max() & df['Area']=='Fanar, Beirut']

Bu 出现以下错误:

TypeError: 无法使用 dtyped [object] 数组执行 'rand_' 和 [bool] 类型的标量

【问题讨论】:

    标签: python pandas data-science


    【解决方案1】:

    由于运算符==& 的优先级添加(),如果需要选择所有列loc 应省略:

    df[(df['Max Temperature']==df['Max Temperature'].max()) & (df['Area']=='Fanar, Beirut')]
    

    或者使用Series.eq:

    df[df['Max Temperature'].eq(df['Max Temperature'].max())&df['Area'].eq('Fanar, Beirut')]
    

    【讨论】:

      【解决方案2】:

      使用&时,必须将条件用括号括起来:

      df.loc[(df['Max Temperature']==df['Max Temperature'].max()) & (df['Area']=='Fanar, Beirut')]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-19
        • 1970-01-01
        • 1970-01-01
        • 2018-11-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多