The Wayback Machine - https://web.archive.org/web/20241126212746/https://www.geeksforgeeks.org/capitalize-first-letter-of-a-column-in-pandas-dataframe/
Open In App

Capitalize first letter of a column in Pandas dataframe

Last Updated : 11 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important.

One might encounter a situation where we need to capitalize any specific column in given dataframe. Let’s see how can we capitalize first letter of a column in Pandas dataframe.

Let’s create a dataframe from the dict of lists.

Python
# Create a simple dataframe 

# importing pandas as pd 
import pandas as pd 


# creating a dataframe 
df = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 
                'B': ['masters', 'graduate', 'graduate', 
                                'Masters', 'Graduate'], 
                'C': [27, 23, 21, 23, 24]}) 

df 

Output:

There are certain methods we can change/modify the case of column in pandas dataframe. Let’s see how can we capitalize first letter of columns using capitalize() method.

Method #1:

Python
# Create a simple dataframe 

# importing pandas as pd 
import pandas as pd 


# creating a dataframe 
df = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 
                'B': ['masters', 'graduate', 'graduate', 
                                'Masters', 'Graduate'], 
                'C': [27, 23, 21, 23, 24]}) 

df['A'] = df['A'].str.capitalize() 

df 

Output:

Method #2:

Using lambda with capitalize() method

Python
# Create a simple dataframe 

# importing pandas as pd 
import pandas as pd 


# creating a dataframe 
df = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 
                'B': ['masters', 'graduate', 'graduate', 
                                'Masters', 'Graduate'], 
                'C': [27, 23, 21, 23, 24]}) 

df['A'] = df['A'].apply(lambda x: x.capitalize()) 
df['A']

Output:

imp1



Previous Article
Next Article

Similar Reads

Python Capitalize First Letter of Every Word in String
In text manipulation in Python, capitalizing the first letter of every word in a string is a common and essential task. This operation enhances the visual presentation of text and is particularly useful when dealing with user input, titles, or any scenario where proper capitalization is desired. In this article, we will explore some approaches to c
3 min read
Create a Pandas DataFrame from a Numpy array and specify the index column and column headers
This article demonstrates multiple examples to convert the Numpy arrays into Pandas Dataframe and to specify the index column and column headers for the data frame. Example 1: In this example, the Pandas dataframe will be generated and proper names of index column and column headers are mentioned in the function. This approach can be used when ther
4 min read
Get column index from column name of a given Pandas DataFrame
Let's learn how to get the index of a column based on its name using the DataFrame.columns attribute and Index.get_loc() method from the pandas library. Index.get_loc() Method Index.get_loc() function finds the index of a specified column name and returns an integer if the column name is unique. Syntax: Index.get_loc(key, method=None, tolerance=Non
2 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Move a Column to First Position in Pandas DataFrame?
Prerequisites: Pandas The basic idea to move a column in a pandas dataframe is to remove the column from its current place and insert it in the desired position. The pandas library offers many useful functions such as pop() and insert(). We will make use of these two functions to manipulate with our dataframe. Functions Used: Pandas Pop() method is
3 min read
How to Get First Column of Pandas DataFrame?
In this article, we will discuss how to get the first column of the pandas dataframe in Python programming language. Method 1: Using iloc[] function This function is used to get the first column using slice operator. for the rows we extract all of them, for columns specify the index for first column. Syntax : dataframe.iloc[:, 0] where. dataframe i
4 min read
Python | Pandas Series.str.capitalize()
Series.str.capitalize() used to capitalize the string elements in pandas series. Series is a type of data structure which is used as same as list in python. Series can contain the different types of data as we want to enter in the series like list. Syntax : Series.str.capitalize() Parameters: None Returns: Series/Index of objects To get the link to
2 min read
Create a DataFrame from a Numpy array and specify the index column and column headers
Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame. Approach : Import the Pandas and Numpy modules. Create a Numpy array. Create list of index values and column values for the DataFrame. Create the DataFrame. Display the DataFrame. Example 1 : # importiong the
2 min read
How to add column sum as new column in PySpark dataframe ?
In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let's discuss the various methods how we add sum as new columns But first, let's create Dataframe for Demonstratio
4 min read
Python - Scaling numbers column by column with Pandas
Scaling numbers in machine learning is a common pre-processing technique to standardize the independent features present in the data in a fixed range. When applied to a Python sequence, such as a Pandas Series, scaling results in a new sequence such that your entire values in a column comes under a range. For example if the range is ( 0 ,1 ) your e
3 min read
Change column names and row indexes in Pandas DataFrame
Given a Pandas DataFrame, let's see how to change its column names and row indexes. About Pandas DataFramePandas DataFrame are rectangular grids which are used to store data. It is easy to visualize and work with data when stored in dataFrame. It consists of rows and columns.Each row is a measurement of some instance while column is a vector which
4 min read
Apply uppercase to a column in Pandas dataframe
Analyzing a real world data is some what difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to uppercase each letter in any specific column in given dataframe. Let's see how
2 min read
How to lowercase strings in a column in Pandas dataframe
Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to lowercase each letter in any specific column in given dataframe. Let's see how to
2 min read
Get n-smallest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-smallest values from a particular column in Pandas DataFrame. Observe this dataset first. We'll use 'Age', 'Weight' and 'Salary' columns of this data in order to get n-smallest value
1 min read
Get n-largest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-largest values from a particular column in Pandas DataFrame. Observe this dataset first. We’ll use ‘Age’, ‘Weight’ and ‘Salary’ columns of this data in order to get n-largest values
1 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
Create a column using for loop in Pandas Dataframe
Adding a new column in an already created dataframe is quite easy. Adding a new column is actually required to process the data of dataframe created earlier. For that purpose, we can process the existing data and make a separate column to store the data. The simplest way to add a new column along with data is by creating a new column and assigning
3 min read
Getting Unique values from a column in Pandas dataframe
Let's see how can we retrieve the unique values from pandas dataframe. Let's create a dataframe from CSV file. We are using the past data of GDP from different countries. You can get the dataset from here. # import pandas as pd import pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csv record = pd.read_csv(gapmi
2 min read
Split a column in Pandas dataframe and get part of it
When a part of any column in Dataframe is important and the need is to take it separate, we can split a column on the basis of the requirement. We can use Pandas .str accessor, it does fast vectorized string operations for Series and Dataframes and returns a string object. Pandas str accessor has number of useful methods and one of them is str.spli
2 min read
Return the Index label if some condition is satisfied over a column in Pandas Dataframe
Given a Dataframe, return all those index labels for which some condition is satisfied over a specific column. Solution #1: We can use simple indexing operation to select all those values in the column which satisfies the given condition. C/C++ Code # importing pandas as pd import pandas as pd # Create the dataframe df = pd.DataFrame({'Date':['10/2
2 min read
Check if a column starts with given string in Pandas DataFrame?
In this program, we are trying to check whether the specified column in the given data frame starts with specified string or not. Let us try to understand this using an example suppose we have a dataset named student_id, date_of_joining, branch. Example: C/C++ Code #importing library pandas as pd import pandas as pd #creating data frame for student
2 min read
How to Convert Dataframe column into an index in Python-Pandas?
Pandas provide a convenient way to handle data and its transformation. Let's see how can we convert a data frame column to row name or index in Pandas. Create a dataframe first with dict of lists. C/C++ Code # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':["Akash", "Geeku", "Pankaj
2 min read
How to Convert Index to Column in Pandas Dataframe?
Pandas is a powerful tool which is used for data analysis and is built on top of the python library. The Pandas library enables users to create and manipulate dataframes (Tables of data) and time series effectively and efficiently. These dataframes can be used for training and testing machine learning models and Analyzing data. Converting Index to
2 min read
How to Sort a Pandas DataFrame based on column names or row index?
Pandas dataframe.sort_index() method sorts objects by labels along the given axis. Basically, the sorting algorithm is applied to the axis labels rather than the actual data in the Dataframe and based on that the data is rearranged. Creating Pandas Dataframe Create a DataFrame object from the Python list of tuples with columns and indices, say colu
3 min read
How to Concatenate Column Values in Pandas DataFrame?
Many times we need to combine values in different columns into a single column. There can be many use cases of this, like combining first and last names of people in a list, combining day, month, and year into a single column of Date, etc. Now we'll see how we can achieve this with the help of some examples. Example 1: In this example, we'll combin
2 min read
Replace all the NaN values with Zero's in a column of a Pandas dataframe
Replacing the NaN or the null values in a dataframe can be easily performed using a single line DataFrame.fillna() and DataFrame.replace() method. We will discuss these methods along with an example demonstrating how to use it. DataFrame.fillna(): This method is used to fill null or null values with a specific value. Syntax: DataFrame.fillna(self,
3 min read
Check whether a given column is present in a Pandas DataFrame or not
Consider a Dataframe with 4 columns : 'ConsumerId', 'CarName', CompanyName, and 'Price'. We have to determine whether a particular column is present in the DataFrame or not in Pandas Dataframe using Python. Creating a Dataframe to check if a column exists in Dataframe C/C++ Code # import pandas library import pandas as pd # dictionary d = {'Consume
2 min read
Finding the Quantile and Decile Ranks of a Pandas DataFrame column
A Quantile is where a sample is divided into equal-sized, adjacent, subgroups. The median is a quantile; the median is placed in a probability distribution so that exactly half of the data is lower than the median and half of the data is above the median. The median cuts a distribution into two equal areas and so it is sometimes called 2-quantile.
4 min read
Percentile rank of a column in a Pandas DataFrame
Let us see how to find the percentile rank of a column in a Pandas DataFrame. We will use the rank() function with the argument pct = True to find the percentile rank. Example 1 : # import the module import pandas as pd # create a DataFrame data = {'Name': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location' : ['Saharanpur', 'Meerut', 'Agr
1 min read
Select all columns, except one given column in a Pandas DataFrame
DataFrame Data structure are the heart of Pandas library. DataFrames are basically two dimension Series object. They have rows and columns with rows representing the index and columns representing the content. Now, let's see how to Select all columns, except one given column in Pandas DataFrame in Python. Creating a DataFrame: C/C++ Code # import p
2 min read
three90RightbarBannerImg