I do have a DataFrame mxn and would like to flip one column in similar way to list flip e.g.:
list1 = [1,2,3,4]
list2 = list1[::1]
so
list2 looks like this: [4,3,2,1]
How to apply something similar 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:
e.g.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With