jstar
jstar

Reputation: 1

How to fill missing values when reindexing a categorical index?

This is my first post to SO, so please forgive my transgressions. I have a dataframe for which I make a categorical index using cut. I then add the missing intervals, like so

n = np.arange(6)
a = [0. , 0.5, 0.7, 0.9, 1. ]
b = [0. , 1. , 2.5, 2.5, 5. ]
df = pd.DataFrame({'a':a, 'b':b} )
df.set_index(pd.cut(df.b, n), inplace=True)
bins = pd.interval_range(0, 5)
df = df.reindex(bins)

          a    b
b               
(0, 1]  0.5  1.0
(1, 2]  NaN  NaN
(2, 3]  0.7  2.5
(2, 3]  0.9  2.5
(3, 4]  NaN  NaN
(4, 5]  1.0  5.0

I want to backfill the NaNs in each column but the argument method is not implemented for CategoricalIndex.reindex. Is there another way to accomplish this? I'm using Pandas 0.22.0

Upvotes: 0

Views: 238

Answers (1)

Naga kiran
Naga kiran

Reputation: 4607

You can use fillna function in pandas with mentioning backfill

df.fillna(method='bfill')

Upvotes: 1

Related Questions