Home > Net >  Pandas reindex dataframe with greater and less than index
Pandas reindex dataframe with greater and less than index

Time:10-05

I have a dataframe df1 as:

idx Col1
2   v2
3   v3
4   v4
5   v5

I want to reindex df1 for values df1.reindex([1, 2, 3, 4, 5, 6]) to get the following:

idx Col1
1   v2
2   v2
3   v3
4   v4
5   v5
6   v5

Where all values less than 2 got the value of index 2, all values higher than 5 got value of index 5 from the dataframe df1

CodePudding user response:

You can try .ffill() .bfill(), as follows:

df1 = df1.reindex([1, 2, 3, 4, 5, 6]).ffill().bfill()

Data Input:

df1 = pd.DataFrame({'Col1': {2: 'v2', 3: 'v3', 4: 'v4', 5: 'v5'}}).rename_axis(index='idx')

    Col1
idx     
2     v2
3     v3
4     v4
5     v5

Result:

print(df1)

    Col1
idx     
1     v2
2     v2
3     v3
4     v4
5     v5
6     v5

Edit:

In case your reindex indices are not in sequence, e.g. [2, 1, 4, 6, 5, 3] you can .sort_index() first then .ffill() .bfill() and reindex again, like below:

df1.reindex([2, 1, 4, 6, 5, 3]).sort_index().ffill().bfill().reindex([2, 1, 4, 6, 5, 3])

Result:

    Col1
idx     
2     v2
1     v2
4     v4
6     v5
5     v5
3     v3

CodePudding user response:

Let us try notice here I am using the nearest with the sorted

out = df.reindex(sorted([1, 2, 3, 4, 5, 6]),method='nearest')
Out[105]: 
    Col1
idx     
1     v2
2     v2
3     v3
4     v4
5     v5
6     v5
  • Related