Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用pandas将整个列字符串转换为数据帧中的浮点?_Python_Pandas_Csv - Fatal编程技术网

Python 如何使用pandas将整个列字符串转换为数据帧中的浮点?

Python 如何使用pandas将整个列字符串转换为数据帧中的浮点?,python,pandas,csv,Python,Pandas,Csv,我的df中有一列名为“大小” df['Size'] 0 19M 1 14 2 8.7 3 25 4 2.8M 5 5.6 我想删除本专栏中的所有M,所以我这样做了 df.Size.str.replace('M','') 它起作用了,但是我还想把这个列中的字符串转换成float 我尝试了df.Size.float.replace('M','') 但我得到了这个错误: AttributeError:“Se

我的df中有一列名为“大小”

df['Size']

0         19M
1         14
2        8.7
3         25
4        2.8M
5        5.6
我想删除本专栏中的所有M,所以我这样做了

df.Size.str.replace('M','')
它起作用了,但是我还想把这个列中的字符串转换成float

我尝试了df.Size.float.replace('M','')

但我得到了这个错误:

AttributeError:“Series”对象没有属性“float”


我该怎么办?

我用
来表示数字

更新

pd.to_numeric(df.Size.replace('M','',regex=True),errors='coerce').fillna(df.Size)
Out[497]: 
0     19
1    14k
2    8.7
3     25
4    2.8
5    5.6
Name: Size, dtype: object

检查此处的转换,只有单元格仍包含k
str
type,所有其他单元格变为
float

pd.to_numeric(df.Size.replace('M','',regex=True),errors='coerce').fillna(df.Size).apply(type)
Out[501]: 
0    <class 'float'>
1      <class 'str'>
2    <class 'float'>
3    <class 'float'>
4    <class 'float'>
5    <class 'float'>
Name: Size, dtype: object

为了安全起见,我们可以使用
regex
删除所有字母:

df['Size'] = df['Size'].str.replace('([A-Za-z])', '', regex=True).astype(float)

print(df)
    Size
0   19.0
1   14.0
2    8.7
3   25.0
4    2.8
5    5.6
6  201.0

没有其他方法可以使用“float”?@lilzuzuzu
df.Size.replace('M','',regex=True)。astype(float)
它给出错误:ValueError:无法将字符串转换为float:'201k'。有些值是以千为单位的,我想保留'k',但我不想要'M'我只想删除'M',因为有些值是以'k'为单位的。我仍然想要这些值
df['Size'] = df['Size'].str.replace('([A-Za-z])', '', regex=True).astype(float)

print(df)
    Size
0   19.0
1   14.0
2    8.7
3   25.0
4    2.8
5    5.6
6  201.0