2

I've tried these codes. I can't find what i missing.

frame = pd.DataFrame(np.arange(9).reshape((3, 3)),index=['a', 'c', 'd'],columns=['Ohio', 'Texas', 'California'])
states = ['Texas', 'Utah', 'California']
frame.reindex(index=['a','b','c','d'],method='ffill',columns=states)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
조영규
  • 21
  • 3

2 Answers2

1

I think it is not implemented for non numeric index values, possible solution if not exist missing values in original data:

df = frame.reindex(index=['a','b','c','d'], columns=states).ffill()
print (df)
   Texas  Utah  California
a    1.0   NaN         2.0
b    1.0   NaN         2.0
c    4.0   NaN         5.0
d    7.0   NaN         8.0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • seems like a similar prob: https://stackoverflow.com/questions/31285508/valueerror-index-must-be-monotonic-increasing-or-decreasing – Raphael Jul 09 '19 at 08:15
0

reindex and method=ffill does implement for string. However, it requires the dataframe/series index and columns must be monotonic increase or decrease when you use method option. frame.columns is non-monotonic, so it fails.

Let try this example by making columns of frame is in lexical order. method=ffill works fine when both index and column are monotonic even though they are strings:

frame = pd.DataFrame(np.arange(9).reshape((3, 3)),index=['a', 'c', 'd'],columns=['California', 'Ohio', 'Texas'])
states = ['Texas', 'Utah', 'California']
frame.reindex(index=['a','b','c','d'],method='ffill',columns=states)

Out[876]:
   Texas  Utah  California
a      2     2           0
b      2     2           0
c      5     5           3
d      8     8           6

If your index and columns are strings and not monotonic, you need to call .ffill, .bfill or .fillna outside after of reindex

Note: this constraint on method option is also applied to numeric index. Just try create a dataframe with numeric non-monotonic index, reindex with method will return the same error.


from docs:

method : {None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘nearest’} Method to use for filling holes in reindexed DataFrame. Please note: this is only applicable to DataFrames/Series with a monotonically increasing/decreasing index.

Andy L.
  • 24,909
  • 4
  • 17
  • 29