Python报错ValueError:无法将字符串转为float请求协助解决
解决pandas创建DataFrame时的ValueError问题
问题原因
你在创建DataFrame时给整个表格指定了dtype=float,但Name列的内容是字符串(比如'Alex'),字符串无法转换为浮点数,因此触发ValueError。
修正方案
方案1:让pandas自动推断列类型
去掉全局的dtype参数,pandas会根据列内容自动识别类型:
import pandas as pd data =[['Alex',18],['John',34],['Wick',27]] df = pd.DataFrame(data, columns=['Name','Age']) print(df)
执行后Name列会被识别为字符串类型,Age列会被识别为整数类型。
方案2:单独指定特定列的类型
如果需要将Age列转为浮点数,可通过字典给指定列设置dtype:
import pandas as pd data =[['Alex',18],['John',34],['Wick',27]] df = pd.DataFrame(data, columns=['Name','Age'], dtype={'Age': float}) print(df)
这样Name列保持字符串类型,Age列被转为浮点数类型。
内容的提问来源于stack exchange,提问作者Suvechha Bhadra
相关产品推荐
相关产品推荐

