将pandas df列中的值除以数字

问题描述

我需要将一列的每个值除以25。下面是我的代码

df['Amount'] = df['Amount'].div(25)

我遇到了一个错误TypeError: unsupported operand type(s) for /: 'str' and 'int' 然后,我尝试使用以下代码将Object数据类型转换为int:

df["Amount"] = df["Amount"].astype(str).astype(int)

错误消息:ValueError: invalid literal for int() with base 10: '0.0'

解决方法

您可以尝试以下方法:

df["Amount"] = df["Amount"]/25
print(df)
,

您可以尝试使用pd.to_numeric函数,如果您希望将其指定为浮点列,则可以尝试使用downcast参数,尽管如果不添加它很可能没问题。

df["Amount"] = pd.to_numeric(df["Amount"],downcast='float')