1

Put zeros make it four digits before the numbers with less than four digits. I have an dataframe like this;

import pandas as pd

data={'Name':['Karan','Rohit','Sahil','Aryan','Zeyd'],'number':[1,0,1111,111,11]}

df=pd.dataframe(data)

and I want to obtain this output:

Name Another header
Karan 0001
Rohit 0000
Sahil 1111
Aryan 0111
Zeyd 0011
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76

2 Answers2

1

IIUC, one approach is to use str.zfill

df["Filled"] = df["number"].astype("string").str.zfill(4)
print(df)

Output

    Name  number Filled
0  Karan       1   0001
1  Rohit       0   0000
2  Sahil    1111   1111
3  Aryan     111   0111
4   Zeyd      11   0011
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

1 possible solution:

import pandas as pd

data={'Name':['Karan','Rohit','Sahil','Aryan','Zeyd'],'number':[1,0,1111,111,11]}

counter = 0
for i in data['number']:
    new = str(i).zfill(4)
    data['number'][counter] = new
    counter += 1

df= pd.DataFrame(data)

print(df)

Might not be the best answer, since I've never worked with Pandas before, but it works

DJ Freeman
  • 399
  • 2
  • 14