首页 > 解决方案 > pandas:TypeError:此 dtype 不允许缩减操作“argmax”

问题描述

python 3.7.6 和 jupyter 笔记本

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

这是奇波

我想找到具有 bigget roder_id的项目

我尝试了很多方法但无法使用此功能

我的方式有什么问题?或者有什么方法可以找到该项目的最大order_id?谢谢!

标签: pythonpandas

解决方案


您需要更改“order_id”的数据类型。看起来它是一个对象类型。您可以使用 dtypes 验证 dtype。

print(chipo.dtypes)

您找不到对象类型的最大值。您可以使用 astype 方法更改列类型并将列转换为整数类型。

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

请注意,如果您现在检查 dtype,则 dtype 现在chipo['order_id']是 int(整数)。

如果您不想永久更改列,则可以实施单行解决方案。

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

最后,作为参考,您应该始终了解您正在处理的列类型。这可以为您节省大量的故障排除。


推荐阅读