I do have a DataFrame mxn and would like to flip one column in similar way to list flip eg:
list1 = [1,2,3,4]
list2 = list1[::1]
so list2 looks like this: [4,3,2,1]
How to apply something similat to a DataFrame to a column but keep order of all rows and other columns so I flip the values in the single column only:
eg
df1 =
col1 col2
1 cat 1
2 dog 2
3 fish 3
4 bird 4
5 mouse 5
to df2
col1 col2
1 cat 5
2 dog 4
3 fish 3
4 bird 2
5 mouse 1
The simplest way of doing this would be:
df.col2 = df.col2.values[::-1]
df
col1 col2
1 cat 5
2 dog 4
3 fish 3
4 bird 2
5 mouse 1
Or, using df.assign
(to return a copy, not as efficient as inplace assignment):
df2 = df.assign(col2=df.col2.values[::-1])
df2
col1 col2
1 cat 5
2 dog 4
3 fish 3
4 bird 2
5 mouse 1
Try concating this to your dataframe.
df1['col2'].loc[::-1]
It should work.
you can do :
>>> df1
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
>>> df1[0]=df1[0].loc[::-1].reset_index(drop=True)
>>> df1
0 1 2
0 7 2 3
1 4 5 6
2 1 8 9
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.