Python | pandas int to string with leading zeros
Last Updated :
27 Sep, 2023
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.
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
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.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read