Home > other >  How can I strip leading zeros from multiple columns in a dataset?
How can I strip leading zeros from multiple columns in a dataset?

Time:07-23

I want to remove leading zeros from 2 columns in the dataset, in a single line of code if possible, but I'm not sure how to write this out. I have this working for a single column.

Dataset before applying regex:

print(excl_merged.head(10))
           Subnet             Mask
0  10.15.176.000  255.255.255.128
1  10.15.177.000  255.255.255.192
2  10.15.178.064  255.255.255.192
3  10.15.179.000  255.255.255.128
4  10.15.180.000  255.255.255.000
5  10.15.181.000  255.255.255.224
6  10.15.182.000  255.255.254.000
7  10.15.183.000  255.255.254.000
8  10.15.184.000  255.255.255.000
9  10.15.185.000  255.255.255.000

Applying regex to single column and Dataset view afterwards:

excl_merged["Subnet"] = excl_merged["Subnet"].str.replace(r"\b0 \B", "", regex=True)
print(excl_merged.head(10))

 Subnet             Mask
0   10.15.176.0  255.255.255.128
1   10.15.177.0  255.255.255.192
2  10.15.178.64  255.255.255.192
3   10.15.179.0  255.255.255.128
4   10.15.180.0  255.255.255.000
5   10.15.181.0  255.255.255.224
6   10.15.182.0  255.255.254.000
7   10.15.183.0  255.255.254.000
8   10.15.184.0  255.255.255.000
9   10.15.185.0  255.255.255.000

CodePudding user response:

You're very close, try this:

Subnet = ["10.15.183.000",  "10.15.184.000", "10.15.185.224"] 
Mask = ["255.255.254.000", "255.255.255.064", "255.255.255.000"]
excl_merged = pd.DataFrame({"Subnet":Subnet, "Mask":Mask})

### Relevant code
excl_merged[["Subnet", "Mask"]] = excl_merged[["Subnet", "Mask"]].replace(r"\b0 \B", "", regex=True)

Output:

Subnet          Mask
10.15.183.0     255.255.254.0
10.15.184.0     255.255.255.64
10.15.185.224   255.255.255.0
  • Related