How to turn a pandas dataframe row into a comma separated string?

Given a pandas dataframe, we have to turn its row into a comma separated string.
Submitted by Pranit Sharma, on November 26, 2022

Prerequisite

  • 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

Suppose we are given the Pandas dataframe and we need to iterate over each row of this data frame and convert this into a comma-separated string.

Turn/Convert a pandas dataframe row into a comma separated string

To convert a pandas dataframe row into a comma separated string, first, we will use the to_string() method of dataframe where we will pass all the required parameters and we will apply the split method so that it will split all the rows, now we have a list containing string values but they are not separated by a comma hence we will use the join method to add a comma in between each of the string in the list.

Let us understand with the help of an example,

Python program to turn a pandas dataframe row into a comma separated string

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame(np.random.randn(5, 2),columns=['a', 'b'])

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

# Converting all the row values into string 
# and putting them all together in a list
res = df.to_string(header=False,index=False,index_names=False).split('\n')

# Adding a comma in between each value of list
res = [','.join(ele.split()) for ele in res]

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

Output

The output of the above program will be:

Example: Turn a pandas dataframe row into a comma separated string

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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