pandas - 值错误: could not convert string to float: '1.598.248'

标签 pandas string dataframe

enter image description here

如何将以百万为单位的数字数据帧列转换为 double 或 float

0   1.598.248
1   1.323.373
2   1.628.781
3   1.551.707
4   1.790.930
5   1.877.985
6   1.484.103

0   15982480.0
1   13233730.0
2   16287810.0
3   15517070.0
4   17909300.0
5   18779850.0
6   14841030.0

最佳答案

您需要删除句号。您可以使用 pandas 替换方法然后将其转换为 float :

df['col'] = df['col'].replace('\.', '', regex=True).astype('float')

示例

>>> df = pd.DataFrame({'A': ['1.1.1', '2.1.2', '3.1.3', '4.1.4']})
>>> df

       A
0  1.1.1
1  2.1.2
2  3.1.3
3  4.1.4

>>> df['col'] = df['col'].replace('\.', '', regex=True).astype('float')
>>> df['A']

       A
0  111.0
1  212.0
2  313.0
3  414.0

>>> df['A'].dtype

float64

我假设因为有两个句号,所以数据的类型为字符串。但是,即使该列中也有一些整数或 float ,这也应该有效。

关于pandas - 值错误: could not convert string to float: '1.598.248' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72541935/

相关文章:

python - PySpark 和方法链

python - 如何在不丢失索引的情况下转换 pandas 中的数据框?

python - Pandas 导入 FRED 数据(pandas.io.data 或 pandas_datareader)

python - 如何使用 Python 减少字符串中的重复字符

python - 使用值列表从 Pandas 数据框中选择行

r - 如何根据条件使用 igraph 更改 R 中的 vertex.shape

python - 系列 : dynamic transposition optimization

java - 如何创建一个具有特定字符前后子字符串名称的文件

java - 将带有字母的字符串数组转换为java中的int数组

python - 有没有办法将多个 Excel 选项卡/工作表从单个 xlsx 读取到多个数据帧,每个数据帧都以工作表名称命名?