How to combine multiple rows of strings into one using pandas?

Learn, how can we combine multiple rows of strings into one using pandas?
Submitted by Pranit Sharma, on November 05, 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.

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.

Problem statement

We are given a DataFrame with one column and this column contains all string values, we need to combine all these values and make them a single string.

Combine multiple rows of strings into one

To combine multiple rows of strings into one using pandas, we will use str.join() method inside which we can pass any delimiter with which we want to separate all the values in a single string.

Let us understand with the help of an example,

Python program to combine multiple rows of strings into one using pandas

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {'word':['Hello',
             'world !',
             'this','is','a','tutorial','of','IncludeHelp']}

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

# Display dataframe
print('Original DataFrame:\n',df,'\n')

# Adding all the values
res = ', '.join(df['word'])

# Display result
print('Result:\n',res,'\n')

Output

The output of the above program is:

Example: Combine multiple rows of strings into one using pandas

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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