Home > Mobile >  How to loop on value in a data frame and insert zeros in the middle
How to loop on value in a data frame and insert zeros in the middle

Time:11-03

I have a value in a column 'ACCOUNT_N0', it consists of 14 digits I want them to be 16 digits by inserting 2 zeros in the middle, one in the 4th position and the other in the 8th position example: This is the value: 33322288888888 The output: 3330222088888888

What i have found is inserting zeros at the beginning of the number, using:

df['ACCOUNT_NO'].astype(str).str.zfill(16)

I want to know how to insert in the 4th position and the 8th position

CodePudding user response:

You can create a function that take in input the digits(as string) and put the '0' in the positions that you want, like this:

def insert_0(text):
    tmp = text
    text = tmp[0:3]   '0'   tmp[3:7]   '0'   tmp[7:]
    return text

And than in the main you call it using DataFrame.apply(), like this:

df['ACCOUNT_NO'] = df['ACCOUNT_NO'].astype(str)
df['ACCOUNT_NO'] = df['ACCOUNT_NO'].apply(insert_0)

Hope it could be useful.

CodePudding user response:

Strings are immutable (you cannot change a string's value). So you can use slicing to add the 0s in the right position as so:

my_str[:4]   "0"   my_str[4:8]   "0"   my_str[8:]

In your pandas dataframe, you could apply this concept like this:

df['ACCOUNT_NO'] = df['ACCOUNT_NO'].astype(str)
df['ACCOUNT_NO'] = df['ACCOUNT_NO'].str[:4]   "0"   df['ACCOUNT_NO'].str[4:8]   "0"   df['ACCOUNT_NO'].str[8:]

Full code:

df = pd.DataFrame(columns=["ACCOUNT_NO"])
df["ACCOUNT_NO"] = ["33322288888888"]
df['ACCOUNT_NO'] = df['ACCOUNT_NO'].astype(str)
df['ACCOUNT_NO'] = df['ACCOUNT_NO'].str[:4]   "0"   df['ACCOUNT_NO'].str[4:8]   "0"   df['ACCOUNT_NO'].str[8:]

Output:

Before

before

After

after

  • Related