pandas astype(float) 作为 int 返回

pandas astype(float) returning as int

我正在通过 DataQuest Data Analyst 路径工作,并且在笔记本电脑数据集上。我正在尝试将列从字符串转换为浮点数(该列包含 cpu 以 GHz 为单位的处理器速度)。

laptops["processor_speed_ghz"] = laptops["cpu"].str.split().str[-1]
laptops["processor_speed_ghz"] = laptops["processor_speed_ghz"].str.replace("GHz", "")
laptops["processor_speed_ghz"] = laptops["processor_speed_ghz"].astype(float)
print(laptops["processor_speed_ghz"].value_counts())

转换工作完美,除了当我检查新列时,它说类型是 int64 而不是 float64。不确定我做错了什么。

这是预期的,因为函数的输出 Series.value_counts return 计数。所以得到索引由浮点数填充的系列,系列的值是整数。

laptops = pd.DataFrame({"processor_speed_ghz":[2.0,3.0, 2.0, 5.0, 3.0, 3.0]})
print (laptops)
   processor_speed_ghz
0                  2.0
1                  3.0
2                  2.0
3                  5.0
4                  3.0
5                  3.0

print(laptops["processor_speed_ghz"].value_counts())
3.0    3
2.0    2
5.0    1
Name: processor_speed_ghz, dtype: int64

print(laptops["processor_speed_ghz"].value_counts().index)
Float64Index([3.0, 2.0, 5.0], dtype='float64')