Open In App

Python | pandas int to string with leading zeros

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, When it comes to data manipulation and data analysis, Panda is a powerful library that provides capabilities to easily encounter scenarios where the conversion of integer to string with leading zeros is needed. In this article, we will discuss How we can convert pandas int to string with leading zeros using Python? with the help of various methods and examples.

Using pandas.Series. map() and string formatting

You can use pandas Series .map() and Python's string formatting to convert integers to strings with the leading zeros. The code uses the Pandas library in Python to create a Series named D with the numeric values and then applies to format using the map() function and the '{:04}'. The format format specifier to pad each value with the leading zeros to have a width of the 4 characters. The result, when printed displays the values of Series D with the zero-padding if necessary.

[tabby title="Python3"][sourcecode language="python3"]import pandas as pd # Create a pandas Series with the given values [7, 15, 346, 68, 8] D = pd.Series([7, 15, 346, 68, 8]) D = D.map('{:04}'.format) # Print the formatted Series print(D) [/sourcecode][tabbyending]

Output:

0    0007
1 0015
2 0346
3 0068
4 0008
dtype: object

Using pandas.Series. str. zfill()

You can utilizes the str.zfill() the method provided by the pandas Series. This method pd the strings in the Series with the leading zeros to specified width. The code utilizes the Pandas library in Python to create a Series named 'D' containing integer values and then converts these integers to the strings pads them with the leading zeros to have a width of 5 characters each and prints the resulting Series. This ensures all values are displayed as 5-character strings with the leading zeros if necessary.

[tabby title="Python3"][sourcecode language="python3"]import pandas as pd # Create a Pandas Series with # given values D = pd.Series([7, 15, 356, 58, 5]) D = D.astype(str).str.zfill(5) # Print the modified Series print(D) [/sourcecode][tabbyending]

Output

0    00007
1 00015
2 00356
3 00058
4 00005
dtype: object

Using .str.format() and F-Strings

The str. format() method in combination with the F-strings a feature introduced in Python 3.6. This method allows you to format strings by incorporating expressions inside curly braces {} within the string. A Pandas Series named GFG is created with values [7, 25, 326, 38, 5] and The .apply() function is used to apply a formatting operation to each element in the GFG Series. A lambda function is provided to format each number with the leading zeros using the F-strings. For example, f"{x:05}" means that each number x should be represented as a string with the width of the 5 characters padded with the leading zeros if needed. The modified Series GFG with formatted values is stored back into variable GFG

[tabby title="Python3"][sourcecode language="python3"]import pandas as pd # Create a Pandas Series with given values GFG = pd.Series([7, 25, 326, 38, 5]) # Use .str.format() with #F-strings to add leading zeros GFG = GFG.apply(lambda x: f"{x:05}") # Print the modified Series print(GFG) [/sourcecode][tabbyending]

Output

0    00007
1 00025
2 00326
3 00038
4 00005
dtype: object

Convert Integers to Strings in Pandas Dataframe with leading zeros

Another way to add leading zero to string ina pandas dataframe is to use the str.pad() method. There is one method in in which strings with a character specified with a width.

Create a sample dataframes Using str.pad() method

The str.pad() methods two arguments: width and fillchar. Dataframes or Seies,'str.pad()' is method used to pad strings inza series to a specified width. In this code we used width that is required for the resultant string. The"side" is used to pad the strings. It can be 'ledt', 'right' or'both'. and "fillchar" is used for padding and default as a space.

[tabby title="Python3"][sourcecode language="python3"]import pandas as pd df = pd.DataFrame({"values":["A","BB"]}) df['padded_values'] = df['values'].str.pad(width=5, side='right', fillchar='0') print(df)[/sourcecode][tabbyending]

Output

 values padded_values
0 A A0000
1 BB BB000

Adding leading zeros using Pandas str.pad() method

You can add leading zeros ti strings in a Pandas dataframes by using str.pad() method. df['padded_values'] = df['values'].str.pad(width=5, side='left', fillchar='0'): This line adds a new column to the DataFrame called 'padded_values'. fillchar='0' is parameter specifies the character used for padding, which is '0' in this case.

[tabby title="Python3"][sourcecode language="python3"]import pandas as pd df = pd.DataFrame({"values": ["A", "BB"]}) df['padded_values'] = df['values'].str.pad(width=5, side='left', fillchar='0') print(df)[/sourcecode][tabbyending]

Output

  values padded_values
0 A 0000A
1 BB 000BB

Conclusion

To convert intergers and strings with leading zeros is required in Data analysis. By exploring these above mentioned methods we came to know that these methods can be achieve using pandas and it is the proficient way to format numerical identifiers or codes in a format. Whether you choose built-in or a custom function, pandas offers a flexibility and ease to handle such conversions.


Next Article
Article Tags :
Practice Tags :

Similar Reads