olafgrossebaf
olafgrossebaf

Reputation: 49

Set value to slice of a Pandas dataframe

I want to sort a subset of a dataframe (say, between indexes i and j) according to some value. I tried

df2=df.iloc[i:j].sort_values(by=...)
df.iloc[i:j]=df2

No problem with the first line but nothing happens when I run the second one (not even an error). How should I do ? (I tried also the update function but it didn't do either).

Upvotes: 1

Views: 1980

Answers (1)

jezrael
jezrael

Reputation: 862771

I believe need assign to filtered DataFrame with converting to numpy array by values for avoid align indices:

df = pd.DataFrame({'A': [1,2,3,4,3,2,1,4,1,2]})
print (df)
   A
0  1
1  2
2  3
3  4
4  3
5  2
6  1
7  4
8  1
9  2

i = 2
j = 7
df.iloc[i:j] = df.iloc[i:j].sort_values(by='A').values
print (df)
   A
0  1
1  2
2  1
3  2
4  3
5  3
6  4
7  4
8  1
9  2

Upvotes: 2

Related Questions