How to display a dataframe while changing one of its column value?

Viewed 47

Let's take this dataframe :

df = pd.DataFrame(dict(Col1=['a','b','c'], Col2=[1,-3,2]))
  Col1  Col2
0    a     1
1    b    -3
2    c     2

I would like to display this dataframe while changing Col2, replacing negative numbers by "neg" and positive ones by "pos".
I could modify the column / add a new column then display or create a new dataframe specially to display that but I wonder if there is a more optimal way to do as I don't want to keep this modification.

I tried the following but I get the error "lambda cannot contain assignment" :

df.apply(lambda x : x['Col2'] = "pos" if x['Col2'] >= 0 else "neg")

Is there please a way to do ?

1 Answers

In agreement with @anky_91 comment, the solution is using df.assign :

df.assign(Col2=np.where(df['Col2'] >= 0 ,'pos','neg'))

Output :

  Col1 Col2
0    a  pos
1    b  neg
2    c  pos
Related