The pandas
library in Python comes with a number of built-in functions to help with common data manipulation tasks. In this tutorial, we will look at how to get a row of a Pandas dataframe as a string with the help of some examples.
How to get a row as a string in Pandas?
To get a pandas row as a string, you can use Pandas’ built-in function to_string()
. The syntax is:
#Obtain the row row = df.iloc[row_number] #Convert the row to a string row_as_string = row.to_string(index=False)
Here,
df
– Pandas DataFrame object.df.iloc[row_number]
– Returns pandas row with the indexrow_number
.row.to_string()
– Returns the row as a string.row.to_string(index=False)
– Returns pandas row as a string without the column names.
In this code, we obtain a row using the iloc
slicing method. This row is actually obtained as a Pandas Series object with the column names of the dataframe becoming its index.
When we convert it to a string using the in-built method to_string()
, the column names (header) are also present in the string.
To remove these column names, pass index=False
as an argument to the to_string()
function. This removes the index from the string, and as said earlier, this index is the header of the dataframe. That means the header of the dataframe is now removed.
Thus, we obtain the required row as a string.
Examples
Let’s understand the above syntax with some code examples.
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
To start, let’s create a dataframe for the marks of students in a class. For simplicity, we will consider only three subjects and three students.
import pandas as pd #Making a dictionary to pass it to dataframe d = {'Anne': [97, 67, 78], 'Mike': [41, 65, 36], 'John': [84, 89, 76]} #DataFrame object is created with index of choice. df = pd.DataFrame(d, index=['Maths', 'Science', 'English']) #Display the dataframe df
Output:
Now we have an example dataframe with subjects being the row labels and students names as column headers.
Example 1: Get the first row of the dataframe as a string
To obtain the first row of a dataframe as a string, we fetch the first row of a dataframe using df.iloc[0]
where 0
indicates the index of the first row of the dataframe. This row is converted to a string using to_string()
function.
#Get the first row first_row = df.iloc[0] #Convert the row to string first_row_as_string = first_row.to_string() # display the result print(first_row_as_string)
Output:
Anne 97 Mike 41 John 84
Here, the code returns a string of the first row values separated by newline characters. We can see the same values in the first row of our dataframe. Note that the resulting string also contains the column names for each of the row values.
To check if the above result is a string or not, we can simply print its type.
print("Type of variable 'first_row_as_string': ", type(first_row_as_string))
Output:
Type of variable 'first_row_as_string': <class 'str'>
The class ‘str’ shows that this is a string object.
If you do not want to include the column names in the resulting string row, pass index=False
to the to_string()
function.
#Get the first row first_row = df.iloc[0] #Convert the row to string first_row_as_string = first_row.to_string(index=False) #Display the result print(first_row_as_string)
Output:
97 41 84
We get the row values without the column headers as a string.
Example 2: Get the last row of a dataframe as a string with values separated by a comma
To get the last row of the dataframe as a string, we simply replace 0
with -1
in df.iloc[0]
. (The index -1
can be used as an index for the last row).
Now, if we need the values to be separated by commas, we can do so using Python string’s built-in replace()
function.
#Get last row of dataframe last_row = df.iloc[-1] #Get last row of dataframe as string last_row_as_string = last_row.to_string(index=False) #Replace '\n' with comma last_row_as_string = last_row_as_string.replace('\n', ',') #Display the result print(last_row_as_string)
Output:
78,36,76
Here, we have printed the last row, which is indicated by the row label “English” in our dataframe.
Example 3: Get any row of dataframe as a string with values separated by comma
To obtain any row in the dataframe, we can simply put the index of the required row in df.iloc[ ]
method.
#Get any row of dataframe row_number = 1 any_row = df.iloc[row_number] #Get any row of dataframe as string any_row_as_string = any_row.to_string(index=False) #Replace '\n' with comma any_row_as_string = any_row_as_string.replace('\n', ',') #Display the result print(any_row_as_string)
Output:
67,65,89
As we see in the dataframe, the above row is the middle row, indicated by the row label “Science” in our dataframe.
Summary
In this tutorial, we looked at the following key aspects for obtaining a row of a dataframe as a string.
- Obtain a row as a string using the
pandas
built-into_string()
function. - To not include the column names (header) in the string, pass
index=False
as an argument to theto_string()
function. - To replace the default separator of the values in the string obtained from the
to_string()
method, use the stringreplace()
method.
You might also be interested in –
- Pandas – Delete rows based on column values
- Pandas DataFrame – Get Row Count
- Pandas – Select first n rows of a DataFrame
- Pandas – Read only the first n rows of a CSV file
- Pandas – Random Sample of Rows
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.