pandas astype(float) returning as int

Viewed 82

I'm working through the DataQuest Data Analyst path and am on the Laptops dataset. I'm trying to convert a column from string to float (the column contains cpu processor speeds in 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())

The conversion works perfectly, except that when I inspect the new column, it says the type is int64 instead of float64. Not sure what I'm doing wrong.

1 Answers

It is expected, because output of function Series.value_counts return number of counts. So get Series with index filled by floats and values of Series are integers.

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')
Related