简体   繁体   中英

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).

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

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