Jeong
Jeong

Reputation: 131

method does not work in reindex()

from pandas import Series, DataFrame
import numpy as np
frame = DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'b', 'c'], columns=['A', 'B', 'C'])
frame2 = frame.reindex(['a', 'b', 'c', 'd'])
frame3 = frame2.reindex(method='ffill')

Then the results are the followings.

frame
   A  B  C
a  0  1  2
b  3  4  5
c  6  7  8

frame2
     A    B    C 
a  0.0  1.0  2.0
b  3.0  4.0  5.0
c  6.0  7.0  8.0
d  NaN  NaN  NaN

frame3
     A    B    C
a  0.0  1.0  2.0
b  3.0  4.0  5.0
c  6.0  7.0  8.0
d  NaN  NaN  NaN

I intended that the result of print(frame3) would be

frame3
    A    B    C
a  0.0  1.0  2.0
b  3.0  4.0  5.0
c  6.0  7.0  8.0
d  6.0  7.0  8.0

What's wrong with my code? Thanks in advance.

Upvotes: 0

Views: 66

Answers (1)

BENY
BENY

Reputation: 323306

Just using ffill

frame3=frame2.ffill()
frame3
Out[1382]: 
     A    B    C
a  0.0  1.0  2.0
b  3.0  4.0  5.0
c  6.0  7.0  8.0
d  6.0  7.0  8.0

Or

frame3 = frame.reindex(['a', 'b', 'c', 'd'],method='ffill')
frame3
Out[1384]: 
   A  B  C
a  0  1  2
b  3  4  5
c  6  7  8
d  6  7  8

The reason, why your method dose not work , cause frame2 and frame3 have the same index, ffill inside the reindex is for the 'new' index, but there is no new index between frame2 and frame3

Upvotes: 1

Related Questions