简体   繁体   中英

index must be monotonic increasing or decreasing

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM