Wesley Skeeter Wesley Skeeter - 1 month ago 11
Python Question

How can I convert a categorical index to a float?

I have a categorical index of wind directions in a pandas dataframe.

print (self.Groups.index)

CategoricalIndex([22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5],
categories=[22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5],
ordered=True, name='Dir', dtype='category')


I am trying to use this index to plot a wind rose eg.

ax.bar(self.Groups.index,self.Groups['wind_speed'])


but I need to convert the index to radians for it to properly display on a polar plot.

Is there a way to convert the the Categorical index to a float?

Answer

You can use the to_numeric function to convert the index. It gives more control of the expected behavior in case of failure.

# Test data
index = pd.CategoricalIndex([22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5],
categories=[22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5],
ordered=True, name='Dir', dtype='category')
index
df = DataFrame([22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5], index=index)

# Converting the index
df.index = pd.to_numeric(df.index)
print(df.index)

# Float64Index([22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5], dtype='float64', name='Dir')
Comments