Python Pandas: Make a new column from string slice of another column

Given a Pandas DataFrame, we have to make a new column from string slice of another column.
Submitted by Pranit Sharma, on August 10, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

In this article, we are going to learn how to make a new column from a string slice of another column?

Making a new column from string slice of another column

The string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.

A string slice is a method of partitioning a string from some point to some point. The string is sliced based on its index, we need to partition the starting index and ending index by using a colon (:).

Let us understand with the help of an example,

Python program to make a new column from string slice of another column

# Importing pandas package
import pandas as pd

# Creating a Dictionary with 25 keys
d = {
    'Model_Name':['M 51', 'S 20', '9 R','X S'],
    'Brand':['Samsung','Samsung','One Plus','Apple']
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrames
print("Original DataFrame :\n",df,"\n")

# Making a new column with string slice
df['New'] = df.Model_Name.str[:1]

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

Example: Make a new column from string slice of another column

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.