Python / Pandas - How to create in the data frame, a column "str" from another numeric, including zero to the left when the value is less than 9

-1

The code I used to create the column is returning with the following error:

  

The truth value of a series is ambiguous. Use a.empty, a.bool (),   a.item (), a.any () or a.all ().

I do not know how to resolve this error.

import pandas as pd
import numpy as np
raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks'],
            'company': ['1st', '1st', '2nd', '2nd'],
            'deaths': ['kkk', 52, '25', 616],
            'battles': [5, 42, 2, 2],
            'size': ['l', 'll', 'l', 'm']}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'deaths', 'battles', 'size'])

def valida_CEP(x):
    if x < 9:
        return '0' + str(x)
    else:
        return str(x)

df['batles_comzero'] = df.apply(valida_CEP(df['battles']),axis=1)

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
    
asked by anonymous 29.06.2017 / 14:25

1 answer

0

A quick way to do this ( TL; DR ):

Creating the new column:

df['com_zeros'] = '0'

Applying condition:

for b in df.itertuples():
    df.com_zeros[b.Index] = '0'+str(b.battles) if b.battles<9 else str(b.battles)

Result:

df
     regiment company deaths  battles size com_zeros
0  Nighthawks     1st    kkk        5    l        05
1  Nighthawks     1st     52       42   ll        42
2  Nighthawks     2nd     25        2    l        02
3  Nighthawks     2nd    616        2    m        02

See the example running on repl.it.

Note:
The example running on repl.it seems to hang, but that is not the case, the pandas load on repl.it is always time consuming.

To suppress warnings on jupyter notebook:

import warnings
warnings.filterwarnings('ignore')
    
29.06.2017 / 15:46