Getting TypeError: reduction operation 'argmax' not allowed for this dtype when trying to use idxmax()

前端 未结 4 1537
[愿得一人]
[愿得一人] 2021-01-07 22:34

When using the idxmax() function in Pandas, I keep receiving this error.

Traceback (most recent call last):
  File \"/Users/username/College/yea         


        
4条回答
  •  既然无缘
    2021-01-07 23:33

    If NaN are present (and we can sort of see this by the stack trace) then when you think you are working with a data frame of numerics, you could well have mixed types, and in particular, a string among numerics. Let me give you 3 code examples, the first 2 work, the last doesn't and is likely your case.

    This represents all numeric data, it will work with idxmax

    the_dict = {}
    the_dict['a'] = [0.1, 0.2, 0.5]
    the_dict['b'] = [0.3, 0.4, 0.6]
    the_dict['c'] = [0.25, 0.3, 0.9]
    the_dict['d'] = [0.2, 0.1, 0.4]
    the_df = pd.DataFrame(the_dict)
    

    This represents a numeric nan, it will work idxmax

    the_dict = {}
    the_dict['a'] = [0.1, 0.2, 0.5]
    the_dict['b'] = [0.3, 0.4, 0.6]
    the_dict['c'] = [0.25, 0.3, 0.9]
    the_dict['d'] = [0.2, 0.1, np.NaN]
    the_df = pd.DataFrame(the_dict)
    

    This could be the exact problem reported by the OP, but if it turns out we have mixed types in any fashion, we will get the error the OP reported.

    the_dict = {}
    the_dict['a'] = [0.1, 0.2, 0.5]
    the_dict['b'] = [0.3, 0.4, 0.6]
    the_dict['c'] = [0.25, 0.3, 0.9]
    the_dict['d'] = [0.2, 0.1, 'NaN']
    the_df = pd.DataFrame(the_dict)
    

提交回复
热议问题