[英]Convert str to float with pandas Python
I need to change all my column data from str to float but the problema is I have numbers and '--'
too. 我需要将所有列数据从str更改为float,但是问题是我也有数字和
'--'
。 I want to change all '--'
to a 0.00
and then my objetivo variable could be work. 我想将所有的
'--'
更改为0.00
,然后我的objetivo变量可以工作。
import pandas as pd
df = pd.read_csv('status.csv')
objetivo = df['BP Booked Imps Budget (lifetime)'].astype(float)
error: ValueError: could not convert string to float: --
错误:
ValueError: could not convert string to float: --
csv: CSV:
BP Booked Imps Budget (lifetime), Imp
--,5555444
--,342345
--,245632
--,2345467
21345,3456
1234,34567
456,324567
123456,7654
--,6543
Along the lines of what you're already doing, you could do 按照您已经在做的事情,您可以做
df['BP Booked Imps Budget (lifetime)'].replace('--', 0).astype(float)
A different approach would be 一种不同的方法是
pd.to_numeric(df['BP Booked Imps Budget (lifetime)'], errors='coerce').fillna(0)
As I understand it, 据我了解,
df['BP Booked Imps Budget (lifetime)'] = df['BP Booked Imps Budget (lifetime)'].apply(lambda x: 0.0 if x == '--' else x)
df['objectivo'] = df['BP Booked Imps Budget (lifetime)'].astype(float)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.