The Wayback Machine - https://web.archive.org/web/20241119221825/https://www.geeksforgeeks.org/align-columns-to-left-in-pandas-python/
Open In App

Align columns to Left in Pandas – Python

Last Updated : 22 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pandas library is useful for performing exploratory data analysis in Python. A pandas dataframe represents data in a tabular format. We can perform operations on the data and display it. In this article, we are going to align columns to the Left in Pandas. When we display the Dataframe, we can align the data in the columns as left, right, or center.

Python DataFrame.style.set_properties() Function Syntax

In order to align columns to the left in Pandas Dataframe, we use the dataframe.style.set_properties() function.

Syntax: Styler.set_properties(subset=None, **kwargs)

Parameters:

  • subsetIndexSlice: A valid slice for data to limit the style application to.
  • **kwargsdict: A dictionary of property, value pairs to be set for each cell.

Returns: selfStyler

Creating Sample DataFrame

The default is right alignment as we can see in the below example.

Python3




# Python code demonstrate creating
# DataFrame from dict and left aligning
import pandas as pd
 
# initialise data of lists.
data = {'Name' : ['Tania', 'Ravi',
                  'Surbhi', 'Ganesh'],
         
        'Articles' : [50, 30, 45, 33],
         
        'Location' : ['Kanpur', 'Kolkata',
                      'Kolkata', 'Bombay']}
 
# Create DataFrame
df = pd.DataFrame(data)
display(df)


Output:

     Name  Articles Location
0 Tania 50 Kanpur
1 Ravi 30 Kolkata
2 Surbhi 45 Kolkata
3 Ganesh 33 Bombay

Align Columns to Left in Pandas in Python

Below are the ways by which we can align columns to left in Pandas in Python:

  • Using dataframe.style.set_properties() Function
  • Using set_table_styles() Function
  • Using to_string() and Justify Parameter
  • Using formatting
  • Using applymap() Function

Align Columns to Left Using set_properties() Function

In this example, the Pandas DataFrame df is styled to left-align its columns using the style.set_properties() method. The resulting styled DataFrame is then displayed using the display() function.

Python3




left_aligned_df = df.style.set_properties(**{'text-align': 'left'})
display(left_aligned_df)


Output:

Name    Articles    Location
Tania 50 Kanpur
Ravi 30 Kolkata
Surbhi 45 Kolkata
Ganesh 33 Bombay

Align Left Columns Using set_table_styles() Function

If we want the column headers aligned left, we use the set_table_styles() function. Here, both the column headers and the content of all the columns are left-aligned.

Python3




left_aligned_df = df.style.set_properties(**{'text-align': 'left'})
 
left_aligned_df = left_aligned_df.set_table_styles(
    [dict(selector='th', props=[('text-align', 'left')])])
 
display(left_aligned_df)


Output:

Name    Articles    Location
Tania 50 Kanpur
Ravi 30 Kolkata
Surbhi 45 Kolkata
Ganesh 33 Bombay

Left Column Alignment Using to_string() and Justify Parameter

In this example, the DataFrame df is converted to a string representation with left-aligned columns using the to_string() method. The resulting string is then printed, followed by a newline for separation.

Python3




print(df.to_string(justify='left', index=False))
print("\n")


Output:

Name    Articles    Location
Tania 50 Kanpur
Ravi 30 Kolkata
Surbhi 45 Kolkata
Ganesh 33 Bombay

Align Left Column Using Formatting

In this example, each cell of the DataFrame df is formatted to a fixed width of 15 characters with left alignment using the applymap() method and a lambda function. The resulting DataFrame formatted_df2 is then displayed.

Python3




formatted_df2 = df.applymap(lambda x: f"{x:<15}")
display(formatted_df2)


Output:

Name    Articles    Location
Tania 50 Kanpur
Ravi 30 Kolkata
Surbhi 45 Kolkata
Ganesh 33 Bombay

Align Left Column Using applymap() Function

In this example, the style attribute of the DataFrame df is modified using the applymap() method with a lambda function. The lambda function applies a left-aligned text style to each cell in the specified columns. The resulting styled DataFrame styled_df3 is then displayed.

Python3




styled_df3 = df.style.applymap(
    lambda x: f"{'text-align: left;':<15}", subset=df.columns)
display(styled_df3)


Output:

Name    Articles    Location
Tania 50 Kanpur
Ravi 30 Kolkata
Surbhi 45 Kolkata
Ganesh 33 Bombay


Previous Article
Next Article

Similar Reads

Python | Pandas Reverse split strings into two List/Columns using str.rsplit()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas provide a method to split string around a passed separator or delimiter. After that, the string can be stored as a list in a seri
3 min read
Highlight the maximum value in last two columns in Pandas - Python
In this article, we will discuss how to highlight the maximum values in Pandas Dataframe. Let's first make a dataframe: Example: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = {'Name': ['Sumit Tyagi', 'Sukritin', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 2
2 min read
Fillna in multiple columns in place in Python Pandas
In this article, we are going to write Python script to fill multiple columns in place in Python using pandas library. A data frame is a 2D data structure that can be stored in CSV, Excel, .dB, SQL formats. We will be using Pandas Library of python to fill the missing values in Data Frame. Fillna in multiple columns inplace First creating a Dataset
3 min read
Python | Pandas DataFrame.columns
This article explores the Pandas DataFrame.columns attribute. A Pandas dataframe is a two-dimensional, mutable, and potentially heterogeneous data structure with labeled rows and columns. It serves as a container for Series objects and is a fundamental structure in Pandas, facilitating various operations with aligned row and column labels. Pandas D
3 min read
Loop or Iterate over all or certain columns of a dataframe in Python-Pandas
Pandas DataFrames facilitate column-wise iteration, allowing convenient access to elements in each column. In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame. Creating Pandas DataframeIn this article, we will use this Dataframe that we have created by using the Pandas package. C/C++ Code # import panda
5 min read
Python | Pandas Split strings into two List/Columns using str.split()
Pandas provide a method to split string around a passed separator/delimiter. After that, the string can be stored as a list in a series or it can also be used to create multiple column data frames from a single separated string. It works similarly to Python's default split() method but it can only be applied to an individual string. Pandas <code
4 min read
Change the order of a Pandas DataFrame columns in Python
When expanding Pandas dataframes with extra columns, the structure may become unwieldy, and the column arrangement might lose its coherence. To enhance the readability of your dataframes, it's common to reorder the columns, placing them in a more logical sequence. In this article, we are going to see how to change the order of dataframe columns in
5 min read
How to sort a Pandas DataFrame by multiple columns in Python?
Sorting is a fundamental operation applied to dataframes to arrange data based on specific conditions. Dataframes can be sorted alphabetically or numerically, providing flexibility in organizing information. This article explores the process of sorting a Pandas Dataframe by multiple columns, demonstrating the versatile capabilities of Pandas in han
6 min read
Python | Delete rows/columns from DataFrame using Pandas.drop()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages which makes importing and analyzing data much easier. In this article, we will how to delete a row in Excel using Pandas as well as delete a column from DataFrame using Pandas. Pandas Data
4 min read
Creating Pivot Table with Multiple Columns using Python Pandas
PythonPandas make data manipulation, representation and analysis easier. Pandas Pivot Tables are used to create spreadsheet-style pivot tables as a DataFrame. The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame. Pivot Table with Multiple Columns using PandasA piv
4 min read
Python Pandas - Check if the interval is open on the left and right side
In pandas Interval.closed_left and Interval.closed_right attributes are used to check if the interval is open on left and right side. Intervals: Closed interval : closed ='both' represents closed interval. The closed interval contains its endpoints. it is of the form [a,b] and it has the condition a<=x<=b.Open interval: closed =' neither' rep
2 min read
Python Pandas - Difference between INNER JOIN and LEFT SEMI JOIN
In this article, we see the difference between INNER JOIN and LEFT SEMI JOIN. Inner Join An inner join requires two data set columns to be the same to fetch the common row data values or data from the data table. In simple words, and returns a data frame or values with only those rows in the data frame that have common characteristics and behavior
3 min read
Difference of two columns in Pandas dataframe
Difference of two columns in pandas dataframe in Python is carried out by using following methods : Method #1 : Using ” -” operator. import pandas as pd # Create a DataFrame df1 = { 'Name':['George','Andrea','micheal', 'maggie','Ravi','Xien','Jalpa'], 'score1':[62,47,55,74,32,77,86], 'score2':[45,78,44,89,66,49,72]} df1 = pd.DataFrame(df1,columns=
2 min read
Split a text column into two columns in Pandas DataFrame
Let's see how to split a text column into two columns in Pandas DataFrame. Method #1 : Using Series.str.split() functions. Split Name column into two different columns. By default splitting is done on the basis of single space by str.split() function. # import Pandas as pd import pandas as pd # create a new data frame df = pd.DataFrame({'Name': ['J
3 min read
Getting frequency counts of a columns in Pandas DataFrame
Given a Pandas dataframe, we need to find the frequency counts of each item in one or more columns of this dataframe. This can be achieved in multiple ways: Method #1: Using Series.value_counts() This method is applicable to pandas.Series object. Since each DataFrame object is a collection of Series object, we can apply this method to get the frequ
2 min read
Join two text columns into a single column in Pandas
Let's see the different methods to join two text columns into a single column. Method #1: Using cat() function We can also use different separators during join. e.g. -, _, " " etc. # importing pandas import pandas as pd df = pd.DataFrame({'Last': ['Gaitonde', 'Singh', 'Mathur'], 'First': ['Ganesh', 'Sartaj', 'Anjali']}) print('Before Join') print(d
1 min read
Split a String into columns using regex in pandas DataFrame
Given some mixed data containing multiple values as a string, let's see how can we divide the strings using regex and make multiple columns in Pandas DataFrame. Method #1: In this method we will use re.search(pattern, string, flags=0). Here pattern refers to the pattern that we want to search. It takes in a string with the following values: \w matc
3 min read
Combining multiple columns in Pandas groupby with dictionary
Let' see how to combine multiple columns in Pandas using groupby with dictionary with the help of different examples. Example #1: # importing pandas as pd import pandas as pd # Creating a dictionary d = {'id':['1', '2', '3'], 'Column 1.1':[14, 15, 16], 'Column 1.2':[10, 10, 10], 'Column 1.3':[1, 4, 5], 'Column 2.1':[1, 2, 3], 'Column 2.2':[10, 10,
2 min read
Show all columns of Pandas DataFrame in Jupyter Notebook
In this article, we will discuss how to show all the columns of a Pandas DataFrame in a Jupyter notebook using Python. Show All Columns and Rows in a Pandas DataFrame Pandas have a very handy method called the get.option(), by this method, we can customize the output screen and work without any inconvenient form of output. Pandas set_option() is us
3 min read
Conditional operation on Pandas DataFrame columns
Suppose you have an online store. The price of the products is updated frequently. While calculating the final price on the product, you check if the updated price is available or not. If not available then you use the last price available. Solution #1: We can use conditional expression to check if the column is present or not. If it is not present
4 min read
Collapse multiple Columns in Pandas
While operating dataframes in Pandas, we might encounter a situation to collapse the columns. Let it be cumulated data of multiple columns or collapse based on some other requirement. Let's see how to collapse multiple columns in Pandas. Following steps are to be followed to collapse multiple columns in Pandas: Step #1: Load numpy and Pandas. Step
2 min read
How to widen output display to see more columns in Pandas dataframe?
In Python, if there are many more number of columns in the dataframe, then not all the columns will be shown in the output display. So, let's see how to widen output display to see more columns. Method 1: Using pandas.set_option() function. This function is used to set the value of a specified option. Syntax: pandas.set_option(pat, value) Returns:
2 min read
Drop rows from Pandas dataframe with missing values or NaN in columns
Pandas provides various data structures and operations for manipulating numerical data and time series. However, there can be cases where some data might be missing. In Pandas missing data is represented by two value: None: None is a Python singleton object that is often used for missing data in Python code. NaN: NaN (an acronym for Not a Number),
4 min read
Get the number of rows and number of columns in Pandas Dataframe
Pandas provide data analysts a variety of pre-defined functions to Get the number of rows and columns in a data frame. In this article, we will learn about the syntax and implementation of few such functions. Method 1: Using df.axes() Method axes() method in pandas allows to get the number of rows and columns in a go. It accepts the argument '0' fo
3 min read
Apply a function to single or selected columns or rows in Pandas Dataframe
In this article, we will learn different ways to apply a function to single or selected columns or rows in Dataframe. We will use Dataframe/series.apply() method to apply a function. Apply a function to single row in Pandas DataframeHere, we will use different methods to apply a function to single rows by using Pandas dataframe. First lets create a
5 min read
Sort rows or columns in Pandas Dataframe based on values
In this article, Let's discuss how to Sort rows or columns in Pandas Dataframe based on values. Pandas sort_values() method sorts a data frame in Ascending or Descending order of passed Column. It's different than the sorted Python function since it cannot sort a data frame and particular column cannot be selected. Syntax: DataFrame.sort_values(by,
7 min read
Get minimum values in rows or columns with their index position in Pandas-Dataframe
Let’s discuss how to find minimum values in rows & columns of a Dataframe and also their index position. a) Find the minimum value among rows and columns : Dataframe.min() : This function returns the minimum of the values in the given object. If the input is a series, the method will return a scalar which will be the minimum of the values in the se
4 min read
Concatenate two columns of Pandas dataframe
Let's discuss how to Concatenate two columns of dataframe in pandas python. We can do this by using the following functions : concat() append() join() Example 1 : Using the concat() method. # importing the module import pandas as pd # creating 2 DataFrames location = pd.DataFrame({'area': ['new-york', 'columbo', 'mumbai']}) food = pd.DataFrame({'fo
1 min read
Count the number of rows and columns of a Pandas dataframe
Pandas allow us to get the shape of the Dataframe by counting the number of rows and columns in the Dataframe. You can try various approaches to learn to count the number of rows and columns in a Pandas. Example: Input: {'name': ['Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura'], 'score': [98, 80, 60, 85, 49, 92], 'age': [20, 25, 22, 24
4 min read
Count the number of rows and columns of Pandas dataframe
In this article, we'll see how we can get the count of the total number of rows and columns in a Pandas DataFrame. There are different methods by which we can do this. Let's see all these methods with the help of examples. Example 1: We can use the dataframe.shape to get the count of rows and columns. dataframe.shape[0] and dataframe.shape[1] gives
2 min read
Practice Tags :
three90RightbarBannerImg