使用 pandas 进行编号和强制将值强制转换为整数,但仍然不起作用

问题描述 投票:0回答:1

当我尝试将数据帧强制为数字时感到困惑。当我查看结构时它似乎有效,但我仍然收到错误:

类型错误:+ 不支持的操作数类型:“int”和“str”

代码:

df = df_leads.apply(pd.to_numeric, errors='coerce') code here

df.info()

退货:

Columns: 133 entries, org_size_1_99 to engagement_Type_webpage visits dtypes: float64(107), int64(26) memory usage: 3.1 MB

下一行代码:

sum(df['target']).astype(int)

返回:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

python pandas string numeric
1个回答
0
投票

数据中的某些值不能被视为数字,因为它们不是数字。您可以在错误本身中看到仍然存在字符串。这意味着你不能在不排除或忽略它们的情况下掩盖这样的陈述。

这是一种更稳定的方法:

df = df_leads.apply(lambda x: pd.to_numeric(x, errors='coerce'))

df.info()

nan_count = df['target'].isnull().sum()
print(f"Number of NaN values in 'target': {nan_count}")

df['target'] = df['target'].fillna(0)

sum_result = df['target'].sum().astype(int)
print(f"Sum of 'target': {sum_result}")
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.