Nice Chang
Nice Chang

Reputation: 137

pandas: TypeError: reduction operation 'argmax' not allowed for this dtype

python 3.7.6 and jupyter notebook

import numpy as np
import pandas as pd

chipo = pd.DataFrame(open('orders_24.csv').read().splitlines())

chipo = chipo[0].str.split('\t',expand=True)

chipo.columns = ['order_id', 'quantity', 'item_name', 'choice_description', 'item_price']

chipo = chipo.drop(labels=0)

chipo

This is chipo

And I want to find the item which has the bigget roder_id:

I tried many ways but can't use this function

What is wrong with my way? Or any way to find the biggest order_id of that item? Thanks!

Upvotes: 0

Views: 3694

Answers (1)

Rookie
Rookie

Reputation: 305

You need to change the dtype of "order_id". It looks like it is an object type. You can verify the dtype with dtypes.

print(chipo.dtypes)

You cannot find a maximum of an object type. You can change the column type with the astype method and convert the column to an integer type.

chipo['order_id'] = chipo['order_id'].astype('int') # Change column type to integer
print(chipo['item_name'].iloc[chipo['order_id'].argmax()]) # Print result

Notice if you check the dtypes now, the dtype of chipo['order_id'] is now an int (integer).

If you don't want to permanently change the column you can implement a single line solution.

print(chipo['item_name'].iloc[chipo['order_id'].astype('int').argmax()])

Finally, for reference, you should always be aware of the column types you are dealing with. This can save you a lot of troubleshooting down the line.

Upvotes: 0

Related Questions