DataFrame英尺-英寸身高列转厘米:astype(float)报错原因排查
问题:英尺-英寸格式身高转厘米时的类型转换错误
原始数据
身高数据格式为英尺-英寸:
0 6-10 1 6-9 2 7-2 3 6-1 4 6-6 ... 4545 6-11 4546 7-1 4547 6-1 4548 7-1 4549 6-3
错误操作
使用str.split('-')拆分后得到列表序列,但直接转换类型时出错:
df = player_data['height'].str.split('-').astype(float)
报错信息:
ValueError: setting an array element with a sequence.
错误原因
str.split('-')返回的是每个元素为双元素列表的Series,pandas无法直接将整个列表转换为单个float值——列表是序列类型,不是单一数值,因此触发类型不匹配的错误。
正确解决方法
方法1:拆分后展开为列再计算
先拆分出英尺和英寸两列,转成数值类型后再计算厘米:
# 拆分身高为英尺、英寸两列 player_data[['feet', 'inches']] = player_data['height'].str.split('-', expand=True) # 转换为浮点型 player_data['feet'] = player_data['feet'].astype(float) player_data['inches'] = player_data['inches'].astype(float) # 计算厘米数(1英尺=30.48cm,1英寸=2.54cm) player_data['height_cm'] = player_data['feet'] * 30.48 + player_data['inches'] * 2.54
方法2:用apply批量处理
自定义转换函数,通过apply对每个身高字符串处理:
def convert_to_cm(height): feet, inches = height.split('-') return float(feet)*30.48 + float(inches)*2.54 player_data['height_cm'] = player_data['height'].apply(convert_to_cm)
内容的提问来源于stack exchange,提问作者idunskyi
相关产品推荐
相关产品推荐

