Using zfill to pad a Colum of numbers based on a string in a column of a dataframe

Viewed 56

I'm trying to zfill based on 2 column's in my Dataframe. The first column is called unit and it only contains 2 strings, 'Metric' and 'Imperial'.

The second column is called closing which has loads of numbers in it. However if Colum one is metric I need the numbers to zfill to 5 and if its imperial i need to zfill to 4. Example: Metric: 23 needs to become 00023. Imperial: 23 needs to become 0023

Basically, if column one (unit) = Metric, then I want to look at column two (closing) and zfill to 5 if column one (unit) = Imperia, then I want to look at column two (closing) and zfill to 4

This is the current code, however I'm getting the error: 'function' object has no attribute 'astype'

df['Unit'] == 'Metric', df['closing'].replace.astype(str).zfill(5)
df['Unit'] == 'Imperial', df['closing'].replace.astype(str).zfill(4)
1 Answers

Considering you have only two choices (Metric, Imperial) to choose from, you could use Numpy where.

Input sample.csv

       Unit  closing
0  Imperial       20
1    Metric      284
2  Imperial     1451
3  Imperial       45
4    Metric     8491
import pandas as pd
import numpy as np

df = pd.read_csv('sample.csv')

df['closing'] = np.where(df['Unit'] == 'Metric',
     df['closing'].astype(str).str.zfill(5),
     df['closing'].astype(str).str.zfill(4),
)

print(df)

Output from df

       Unit closing
0  Imperial    0020
1    Metric   00284
2  Imperial    1451
3  Imperial    0045
4    Metric   08491
Related