【问题标题】:How to select a field from a dataframe if a particular condition is achieved?如果达到特定条件,如何从数据框中选择字段?
【发布时间】:2019-09-08 18:16:25
【问题描述】:

我有一个场景,我在 csv 文件中有一些数据,我检索了它并存储在数据框中。现在我需要根据特定条件遍历每一行。如果满足该条件,那么我需要检索该行的一个字段。

例如: 我在数据框中有与板球运动员相关的数据。现在我想选择击球率最高的球员的名字。

谁能帮我解决这个问题?

print("The best Batsman of the Tournament could possibly be: ",
      dataset['Names'].loc[(dataset['Average'] == max(dataset['Average'])) & (dataset['Innings'] >= 15)])

预期输出必须是总得分最高的玩家,例如 Virat Kohli 等...

我得到了输出,但有一些小错误,如下所示: 锦标赛最佳击球手可能是:2 Virat Kohli 名称:名称,数据类型:对象

这里我不想在 ':' 之后打印任何内容,除了 'Virat kohli'。

【问题讨论】:

    标签: python python-3.x pandas csv dataframe


    【解决方案1】:

    如果确定匹配,可以在Innings中的条件后使用idxmax()

    print("The best Batsman of the Tournament could possibly be: ",
      df.loc[df.loc[df.Innings>=15,'Average'].idxmax(),'Names'])
    

    输出

    The best Batsman of the Tournament could possibly be:  Virat Kohli
    

    【讨论】:

    • 当我尝试使用上面相同的代码时:print("The Leading Wicket taker of the Tournament could well be: ", dataset.loc[dataset.loc[dataset['Wickets']].idxmax(),'Names']) 我收到以下错误:TypeError: reduction operation 'argmax' not allowed for this dtype 不知道为什么!跨度>
    • @Vivek 如果Wickets 列的dtype 是object,它会抛出错误,如果我理解正确,它应该是int。检查这个:stackoverflow.com/questions/49767084/…
    【解决方案2】:

    您已经接近但需要正确使用语法。使用:

    print("The best Batsman of the Tournament could possibly be: ",
          dataset.loc[(dataset['Average'] == dataset['Average'].max()) & (dataset['Innings'] >= 15), ['Names']].iloc[0])
    

    不要使用max(dataset['Average']),而是使用dataset['Average'].max(),因为它更快。 loc 还允许您指定所需的列,因此 ['Names']iloc 可以检索第一个元素

    【讨论】:

      【解决方案3】:

      如果没有匹配到值应该有问题,然后idxmax错误地返回第一个值,最好在这里使用nextiter

      a =  dataset.loc[(dataset['Average'] == dataset['Average'].max()) & 
                       (dataset['Innings'] >= 15), 'Names']
      print("The best Batsman of the Tournament could possibly be:
                                     {}".format(next(iter(a), 'no match')))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-21
        • 2023-03-04
        • 1970-01-01
        • 2021-04-26
        • 1970-01-01
        相关资源
        最近更新 更多