无法在 pandas 中将字符串转换为浮点数
Can't convert string into float in pandas
我正在努力将我的 df['High']
转换为 float
,我不确定我做错了什么或是否有其他方法可以转换它们。非常感谢。
df.info()
以最高价、最低价、交易量作为对象类型的详细信息
错误代码
这是因为您在该列中有一个 '-'
。同样,更改为 ''
的空字符串也不会转换为浮点数。您不能将其转换为浮点数,因为它显然不是浮点数。
您可以将 '-'
替换为 nan
import pandas as pd
import numpy as np
df = pd.DataFrame({'High':['20.1','100.3','99','-']})
df['High'] = df['High'].replace('-', np.nan)
df['High'] = df['High'].astype(float)
输出:
之前:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 High 4 non-null object
dtypes: object(1)
memory usage: 160.0+ bytes
之后:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 High 3 non-null float64
dtypes: float64(1)
memory usage: 160.0 bytes
我正在努力将我的 df['High']
转换为 float
,我不确定我做错了什么或是否有其他方法可以转换它们。非常感谢。
df.info()
以最高价、最低价、交易量作为对象类型的详细信息
错误代码
这是因为您在该列中有一个 '-'
。同样,更改为 ''
的空字符串也不会转换为浮点数。您不能将其转换为浮点数,因为它显然不是浮点数。
您可以将 '-'
替换为 nan
import pandas as pd
import numpy as np
df = pd.DataFrame({'High':['20.1','100.3','99','-']})
df['High'] = df['High'].replace('-', np.nan)
df['High'] = df['High'].astype(float)
输出:
之前:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 High 4 non-null object
dtypes: object(1)
memory usage: 160.0+ bytes
之后:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 High 3 non-null float64
dtypes: float64(1)
memory usage: 160.0 bytes