错误:aggreg没有数字类型

2024-09-29 01:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含5列的数据帧,其中需要聚合的列是一个字符串,并且具有NaN值。 我尝试将nan值替换为0,然后将列转换为数字,但在执行gruopby和aggregate函数时仍然得到“DataError:No numeric types to aggregate”。你知道吗

df.head()

df['Profit (in millions)']= df['Profit(in millions)'].str.replace('N.A', '0')
pd.to_numeric(df['Profit (in millions)'], errors ='ignore')
df_new = df.groupby('Year')['Profit (in millions)'].median()
df_new.head(7)

enter image description here

错误: enter image description here


Tags: to数据字符串indfnew数字nan
1条回答
网友
1楼 · 发布于 2024-09-29 01:32:20

有两个问题,您忘记了赋值,如果errors ='ignore'和列中至少有一个不可赋值的值,它将返回没有更改的列:

pd.to_numeric(df['Profit (in millions)'], errors ='ignore')

^{}

errors : {'ignore', 'raise', 'coerce'}, default 'raise'

If 'raise', then invalid parsing will raise an exception
If 'coerce', then invalid parsing will be set as NaN
If 'ignore', then invalid parsing will return the input

所以使用errors ='coerce'并将输出返回到列:

df['Profit (in millions)'] = pd.to_numeric(df['Profit (in millions)'], errors ='coerce')

相关问题 更多 >