The Wayback Machine - https://web.archive.org/web/20241126230247/https://www.geeksforgeeks.org/split-a-column-in-pandas-dataframe-and-get-part-of-it/
Open In App

Split a column in Pandas dataframe and get part of it

Last Updated : 21 Jan, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.split, it can be used with split to get the desired part of the string. To get the nth part of the string, first split the column by delimiter and apply str[n-1] again on the object returned, i.e. Dataframe.columnName.str.split(" ").str[n-1].

Let’s make it clear by examples.

Code #1: Print a data object of the splitted column.




import pandas as pd
import numpy as np
df = pd.DataFrame({'Geek_ID':['Geek1_id', 'Geek2_id', 'Geek3_id', 
                                         'Geek4_id', 'Geek5_id'],
                'Geek_A': [1, 1, 3, 2, 4],
                'Geek_B': [1, 2, 3, 4, 6],
                'Geek_R': np.random.randn(5)})
  
# Geek_A  Geek_B   Geek_ID    Geek_R
# 0       1       1  Geek1_id    random number
# 1       1       2  Geek2_id    random number
# 2       3       3  Geek3_id    random number
# 3       2       4  Geek4_id    random number
# 4       4       6  Geek5_id    random number
  
print(df.Geek_ID.str.split('_').str[0])


Output:

0    Geek1
1    Geek2
2    Geek3
3    Geek4
4    Geek5
dtype: object

 
Code #2: Print a list of returned data object.




import pandas as pd
import numpy as np
df = pd.DataFrame({'Geek_ID':['Geek1_id', 'Geek2_id', 'Geek3_id',
                                         'Geek4_id', 'Geek5_id'],
                'Geek_A': [1, 1, 3, 2, 4],
                'Geek_B': [1, 2, 3, 4, 6],
                'Geek_R': np.random.randn(5)})
  
# Geek_A  Geek_B   Geek_ID    Geek_R
# 0       1       1  Geek1_id    random number
# 1       1       2  Geek2_id    random number
# 2       3       3  Geek3_id    random number
# 3       2       4  Geek4_id    random number
# 4       4       6  Geek5_id    random number
  
print(df.Geek_ID.str.split('_').str[0].tolist())


Output:

['Geek1', 'Geek2', 'Geek3', 'Geek4', 'Geek5']

 
Code #3: Print a list of elements.




import pandas as pd
import numpy as np
  
df = pd.DataFrame({'Geek_ID':['Geek1_id', 'Geek2_id', 'Geek3_id',
                                         'Geek4_id', 'Geek5_id'],
                'Geek_A': [1, 1, 3, 2, 4],
                'Geek_B': [1, 2, 3, 4, 6],
                'Geek_R': np.random.randn(5)})
  
# Geek_A  Geek_B   Geek_ID    Geek_R
# 0       1       1  Geek1_id    random number
# 1       1       2  Geek2_id    random number
# 2       3       3  Geek3_id    random number
# 3       2       4  Geek4_id    random number
# 4       4       6  Geek5_id    random number
  
print(df.Geek_ID.str.split('_').str[1].tolist())


Output:

['id', 'id', 'id', 'id', 'id']


Previous Article
Next Article

Similar Reads

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
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
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
Split Pandas Dataframe by column value
Sometimes in order to analyze the Dataframe more accurately, we need to split it into 2 or more parts. The Pandas provide the feature to split Dataframe according to column index, row index, and column values, etc. Let' see how to Split Pandas Dataframe by column value in Python? Now, let's create a Dataframe: villiers C/C++ Code # importing pandas
3 min read
Split Pandas Dataframe by Column Index
Pandas support two data structures for storing data the series (single column) and dataframe where values are stored in a 2D table (rows and columns). To index a dataframe using the index we need to make use of dataframe.iloc() method which takes Syntax: pandas.DataFrame.iloc[] Parameters:Index Position: Index position of rows in integer or list of
3 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
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
Get list of column headers from a Pandas DataFrame
In this article, we will see, how to get all the column headers of a Pandas DataFrame as a list in Python. The DataFrame.column.values attribute will return an array of column headers. Using list() Get Column Names as List in Pandas DataFrame In this method we are using Python built-in list() function the list(df.columns.values), function. C/C++ Co
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
Get a list of a particular column values of a Pandas DataFrame
In this article, we'll see how to get all values of a column in a pandas dataframe in the form of a list. This can be very useful in many situations, suppose we have to get the marks of all the students in a particular subject, get the phone numbers of all the employees, etc. Let's see how we can achieve this with the help of some examples. Pandas
3 min read
Get a list of a specified column of a Pandas DataFrame
In this discussion, we'll delve into the procedures involved in Get a list of a specified column of a Pandas DataFrame. Our journey commences with the essential task of importing data from a CSV file into a Pandas DataFrame. This initial step establishes the groundwork necessary to create an environment conducive to subsequent data manipulations. G
5 min read
Get unique values from a column in Pandas DataFrame
The unique() function removes all duplicate values on a column and returns a single value for multiple same values. In this article, we will discuss how we can get unique values from a column in Pandas DataFrame. # Get the unique values of any columndf.ColumnName.unique()Pandas Unique Values in ColumnCreating a Pandas Dataframe with Duplicate Eleme
5 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
Split single column into multiple columns in PySpark DataFrame
pyspark.sql.functions provide a function split() which is used to split DataFrame string Column into multiple columns. Syntax: pyspark.sql.functions.split(str, pattern, limit=- 1) Parameters: str: str is a Column or str to split.pattern: It is a str parameter, a string that represents a regular expression. This should be a Java regular expression.l
4 min read
PySpark - Split dataframe by column value
A distributed collection of data grouped into named columns is known as a Pyspark data frame in Python. There occurs various circumstances in which you need only particular rows in the data frame. For this, you need to split the data frame according to the column value. This can be achieved either using the filter function or the where function. In
3 min read
Spark dataframe - Split struct column into two columns
In this article, we are going to learn how to split the struct column into two columns using PySpark in Python. Spark is an open-source, distributed processing system that is widely used for big data workloads. It is designed to be fast, easy to use, and flexible, and it provides a wide range of functionality for data processing, including data tra
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
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
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
Split large Pandas Dataframe into list of smaller Dataframes
In this article, we will learn about the splitting of large dataframe into list of smaller dataframes. This can be done mainly in two different ways : By splitting each rowUsing the concept of groupby Here we use a small dataframe to understand the concept easily and this can also be implemented in an easy way. The Dataframe consists of student id,
3 min read
Split dataframe in Pandas based on values in multiple columns
In this article, we are going to see how to divide a dataframe by various methods and based on various parameters using Python. To divide a dataframe into two or more separate dataframes based on the values present in the column we first create a data frame. Creating a DataFrame for demonestration C/C++ Code # importing pandas as pd import pandas a
3 min read
How to Split Explode Pandas DataFrame String Entry to Separate Rows
Sometimes when working with data, one may encounter a situation where the string entries present in the data frame need to be split into different rows. This can be a challenging task especially when the data is large and complex. Still, a Python library known as pandas provides various functions using which this task can be accomplished easily and
4 min read
Split Pandas Dataframe by Rows
In this article, we will explore the process of Split Pandas Dataframe by Rows. The Pandas DataFrame serves as the focal point, and throughout this discussion, we will experiment with various methods to Split Pandas Dataframe by Rows. Split Pandas DataFrame by Rows In this article, we will elucidate several commonly employed methods for Split Panda
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
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
Determine Period Index and Column for DataFrame in Pandas
In Pandas to determine Period Index and Column for Data Frame, we will use the pandas.period_range() method. It is one of the general functions in Pandas that is used to return a fixed frequency PeriodIndex, with day (calendar) as the default frequency. Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None) Parameters:start : Left bound for
2 min read
How to Sort a Pandas DataFrame by Both Index and Column?
In this article, we will discuss how to sort a Pandas dataframe by both index and columns. Sort DataFrame based on IndexWe can sort a Pandas DataFrame based on Index and column using sort_index method. To sort the DataFrame based on the index we need to pass axis=0 as a parameter to sort_index method.To sort the DataFrame based on the column name t
3 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 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
three90RightbarBannerImg