1

Good morning.

I've a little problem and I'm sure that it has an easy solution, but I can't find it.

I've a dataframe like this:

df = 
    num        unit
0    10     minutes
1    20     seconds
2    30     newtons
3    10     seconds

And, for reasons that doesn't matter, I want to rewrite the num column adding it corresponding unit, getting the next result:

df = 
             num     unit
0   '10 minutes'  minutes
1   '20 seconds'  seconds
2   '30 newtons'  newtons
3   '10 seconds'  seconds

I'm using the following code:

df.num = df.num.apply(lambda x: '{n} {u}'.format(n = x, u = unidecode(df.loc[df[df.num == x].index.values[0], 'unit'])))

The problem comes when there are 2 or more equal values in the first column, like in rows 0 and 3, so my wrong final result, due to ...values[0], is:

df = 
             num     unit
0   '10 minutes'  minutes
1   '20 seconds'  seconds
2   '30 newtons'  newtons
3   '10 minutes'  seconds

Thanks you very much in advance.

Á. Garzón
  • 345
  • 2
  • 15
  • [When should I ever want to use pandas `apply` in my code?](https://stackoverflow.com/questions/54432583/when-should-i-ever-want-to-use-pandas-apply-in-my-code) Spoiler: usually never. – cs95 Feb 07 '19 at 10:59

1 Answers1

2

Apply here is not necessary, convert column to strings and join with :

df['num'] = df['num'].astype(str) + ' ' + df['unit']
print (df)
          num     unit
0  10 minutes  minutes
1  20 seconds  seconds
2  30 newtons  newtons
3  10 seconds  seconds

If need apply for some reason use DataFrame.apply with axis=1 for processes by rows and working with scalars, so convert integer to strings by str:

df['num'] = df.apply(lambda x: str(x['num']) + ' ' + x['unit'], axis=1)
#alternative
#df['num'] = df.apply(lambda x: ' '.join([str(x['num']), x['unit']]), axis=1)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Such a nice answer! I finally use your second approach (I didnt' know about the possibility of use `axis = 1` inside apply) cause I really need use apply, it wors perfectly. – Á. Garzón Feb 07 '19 at 10:53