Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert a single column in a DataFrame

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
like image 789
Dariusz Krynicki Avatar asked Sep 15 '17 16:09

Dariusz Krynicki


1 Answers

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
like image 140
cs95 Avatar answered Sep 22 '22 17:09

cs95