在熊猫中将字符串转换为浮点数

时间:2020-12-30 17:13:10

标签: python pandas dataframe

enter image description here

我想将字符串转换为浮点值,但有一个逗号 (",") 需要删除一些值。

我试过了:

new_df = new_df[['Eleven', 'Twelve', 'Thirteen', 'Fourteen']].str.replace(',', " ").astype(float) 

但它给了我一个错误:

AttributeError: 'DataFrame' object has no attribute 'str'

谁能帮我解决这个问题?

2 个答案:

答案 0 :(得分:2)

尝试带有 replace 选项的 regex=True

new_df = (new_df[['Eleven', 'Twelve', 'Thirteen', 'Fourteen']]
               .replace(',', '', regex=True)
               .astype(float)
         )

或者使用apply

new_df = (new_df[['Eleven', 'Twelve', 'Thirteen', 'Fourteen']]
               .apply(lambda x: x.str.replace(',', ''))
               .astype(float)
         )

答案 1 :(得分:0)

您只能在 Pandas 系列中应用 str 方法。

您可以为几列尝试此操作:

new_df = new_df[['Eleven', 'Twelve', 'Thirteen', 'Fourteen']].apply(lambda x : x.replace(",","").astype(float)