You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中对DataFrame值除以255时出现TypeError的解决咨询

问题

在对pandas DataFrame的值除以255进行归一化时,遇到如下TypeError:

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

相关代码片段:

import pandas as pd
from keras.utils import to_categorical

# Read the CSV file
df = pd.read_csv('C:/Users/NESLİHAN/Desktop/project/data.csv', encoding='latin-1', on_bad_lines='skip')

# Check data types of columns
print(df.dtypes)

# Convert relevant columns to numeric
# Assuming 'column_name' is the column you want to convert
df['column_name'] = pd.to_numeric(df['column_name'], errors='coerce')

# Drop the 'label' column
x = df.drop('label', axis=1)

# Convert x to numpy array after handling data types
x = x.to_numpy()

# Normalize the values by dividing by 255
x = x / 255.0

# Assuming 'label' is the target variable
y = df['label']
y = to_categorical(y)

已通过df.dtypes检查列类型,也尝试转换了单个列,但仍报错,需要解决归一化的问题。

解决方案

1. 批量转换所有特征列为数值类型

你当前只转换了单个column_name,但x(即去掉label后的DataFrame)中可能还有其他字符串类型的列,导致数组中混合了字符串与数值,触发除法错误。需要批量处理所有特征列:

# 先分离特征与标签,再批量转换特征列为数值类型
x = df.drop('label', axis=1).apply(pd.to_numeric, errors='coerce')
y = df['label']

errors='coerce'会将无法转换为数值的内容转为NaN,方便后续处理。

2. 处理转换产生的NaN值

转换后生成的NaN会影响后续计算,可根据需求选择处理方式:

  • 删除含NaN的行(需同步处理标签,避免特征与标签不匹配):
    valid_indices = x.dropna().index
    x = x.loc[valid_indices].to_numpy()
    y = y.loc[valid_indices]
    
  • 用均值填充NaN:
    x = x.fillna(x.mean()).to_numpy()
    

3. 验证数据类型

转换后可再次确认所有特征列的类型,确保无字符串残留:

print(x.dtypes)

完整修正后的代码

import pandas as pd
from keras.utils import to_categorical

# 读取数据
df = pd.read_csv('C:/Users/NESLİHAN/Desktop/project/data.csv', encoding='latin-1', on_bad_lines='skip')

# 分离特征与标签,批量转换特征列为数值类型
x = df.drop('label', axis=1).apply(pd.to_numeric, errors='coerce')
y = df['label']

# 处理NaN值(示例:删除含NaN的行)
valid_indices = x.dropna().index
x = x.loc[valid_indices].to_numpy()
y = y.loc[valid_indices]

# 归一化
x = x / 255.0

# 标签转独热编码
y = to_categorical(y)

内容的提问来源于stack exchange,提问作者nesly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 06:22:56