2

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 ?

Ewdlam
  • 875
  • 9
  • 28
  • 1
    `df['Col2'] = np.where(df['Col2'] >= 0 ,'pos','neg')` you dont need apply for this actually , to just display and not modify use same with assign which returns a copy : `df.assign(Col2=np.where(df['Col2'] >= 0 ,'pos','neg'))` – anky Mar 25 '20 at 14:47
  • 2
    Do not delete the question! That defeats the purpose of Stack Overflow! – Prune Mar 25 '20 at 14:50
  • 1
    I had closed it as a duplicate of https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column , not sure why was this reopened – anky Mar 25 '20 at 14:55
  • I don't see why it is duplicate of this ? There is no df.assign in this post – Ewdlam Mar 25 '20 at 14:57
  • i see what you mean , i was more focussed on the code not working part of it. I will post an answer – anky Mar 25 '20 at 15:01
  • I wrote one, do you want I delete it in order to you wrote yours ? – Ewdlam Mar 25 '20 at 15:02
  • 1
    @Ewdlam thats fine as long as the question is answered :) – anky Mar 25 '20 at 15:04
  • Fine, I just didn't want to steal your up votes ;) – Ewdlam Mar 25 '20 at 15:05

1 Answers1

1

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
Ewdlam
  • 875
  • 9
  • 28