Using pandas.Series.to_string()
we can convert a Series to a String. Series is a One-dimensional ndarray with axis labels. The row labels of the Series are called the index.
Since the Series can have only one column, we can easily convert Series to list, Series to NumPy Array, and Series to Python Dictionary, and even Series to String. In this article, I will explain what is Pandas Series.to_string()
function, syntax, and how to get Pandas Series as a String with examples.
Key Points –
- Use the
astype
method in Pandas to convert a Series to string by specifying the target type as ‘str’. - Employ the
apply
function along with thestr
method to transform each element of a Pandas Series into its string representation. - Transform a Pandas Series to a string representation using the
map
function with thestr
method. - Achieve Series-to-string conversion by concatenating the Series with an empty string using the
+
operator. - Directly convert a Pandas Series to a string representation using the
to_string
method.
1. Quick Examples of Converting Series to String
If you are in a hurry, below are some quick examples of how to convert a Series to a string.
# Quick examples of converting series to string
# Example 1: convert Series to string
str = ser.to_string()
# Example 2: convert Series to string without index
str = ser.to_string(index = False)
# Example 3: Convert Pandas Series int dtype to string
str = ser.to_string()
# Example 4: Convert Series to string list
str = ser.astype(str).tolist()
# Example 5: Using Series.astype() to convert
# DataFrame column to string
df["Fee"]=df["Fee"].values.astype('string')
2. Syntax of Series.to_string()
Following is the syntax of Pandas Series.to_string()
function.
# Syntax of Series.to_string()
Series.to_string(buf=None, na_rep=’NaN’, float_format=None, header=True, index=True, length=False, dtype=False, name=False, max_rows=None)
2.1 Parameters
Following are the parameters of the Series.to_string() function.
buf
– Optional, default isNone
. Can be a writable buffer or anio.StringIO
object.na_rep
– string representation of NAN to use, default ‘NaN’float_format
– formatter function to apply to columns’ elements if they are floating default Noneheader
– It provides Series header (index name)index
– Defines index (row) labels, default Truelength
– Represents the Series lengthdtype
– Add the Series dtypename
– Add the Series name if not Nonemax_rows
– Maximum number of rows
2.2 Return Value
It returns a formatted string.
3. Pandas Convert Series to String
The to_string()
function is used to provide a string representation of the given series object which ideally converts Pandas Series to string.
# create a series
import pandas as pd
ser = pd.Series(["Spark", "PySpark", "Hadoop", "Python", "Pandas"], dtype="string")
print("Create Pandas Series:\n", ser)
print("Type of the object:\n", type(ser))
Yields below output.
3.1 Convert Pandas Series to String
Let’s convert Pandas Series to string using the ser.to_string()
function. For that, we need to call this function along with the given Series, it will convert the given Series into a String object.
# convert Series to string
str = ser.to_string()
print("After converting a Series to string:\n", str)
print("Type of the object:\n", type(str))
Yields below output.
3.2 Convert Pandas Series to String without Index
You can also convert Series to strings without index using the to_string()
function. For that we need to set the Index
param as False
in this function, it will return the given Pandas Series into string representation without index.
# convert Series to string without index
str = ser.to_string(index = False)
print("After converting a Series to string:\n", str)
# Output:
# After converting a Series to string:
# Spark
# PySpark
# Hadoop
# Python
# Pandas
In the above example, we have converted a string dtype series to a string.
3.3 Convert int dtype of Series into String
So far, we have seen string dtype Series converted into string object using to_string()
function. Let’s see another example of converting int dtype Series into a string object using this function. Create Pandas Series using a list of int datatype values and convert those values into string type.
Let’s create the Pandas Series,
# create a series with int datatype
ser = pd.Series([22000, 25000, 23000, 24000, 26000], dtype="int64")
print("Create Pandas Series:\n", ser)
print(type(ser))
# Output:
# Create Pandas Series:
# 0 22000
# 1 25000
# 2 23000
# 3 24000
# 4 26000
# dtype: int64
# <class 'pandas.core.series.Series'>
Let’s convert it to String.
str = ser.to_string()
print("After converting a Series to string:\n", str)
print("Type of the object:\n", type(str))
# Output:
# After converting a Series to string:
# 0 22000
# 1 25000
# 2 23000
# 3 24000
# 4 26000
# Type of the object:
<class 'str'>
4. Convert Pandas Series to String List
You can also convert a Series into a string list using the astype()
function and the tolist()
function. Let’s apply these functions over the given Series, it will return the list of string values.
# Convert Series to string list
str = ser.astype(str).tolist()
print("After converting a Series to string:\n", str)
print("Type of the object:\n", type(str))
# Output:
# After converting a Series to string:
# ['Spark', 'Hadoop', 'pandas', 'Python', 'PySpark']
# Type of the object:
# <class 'str'>
5. Convert Specific Column to String
You can also use Series.astype()
to convert a specific column of DataFraem to a string. Since each column on DataFrame is a pandas Series, I will get the column from DataFrame as a Series and use the astype()
function to get it as a String. In the below example df.Fee
or df['Fee']
returns Series object.
Let’s create DataFrame using data from the Python Dictionary.
# Create DataFrame
import pandas as pd
import numpy as np
technologies= ({
'Courses':["Spark","PySpark","Hadoop","Python","Pandas","Hadoop","Spark"],
'Fee' :[22000,25000,23000,24000,26000,25000,25000],
'Duration':['30day','50days','55days','40days','60days','35day','55days'],
'Discount':[1000,2300,1000,1200,2500,1300,1400]
})
df = pd.DataFrame(technologies)
Apply the astype() function over the specified column in which, we want to convert the string dtype of a given DataFrame, it will return the specified column of DataFrame into a string representation of the object.
# Using Series.astype() to convert
# DataFrame column to string
df["Fee"]=df["Fee"].values.astype('string')
print(df.dtypes)
# Output:
# Courses object
# Fee string
# Duration object
# Discount int64
# dtype: object
Frequently Asked Questions on Convert Pandas Series to String
You can convert a Pandas Series to a string using various methods. Two common approaches are using the astype
method or applying the str
method through functions like map
or apply
. Additionally, the to_string
method can be directly applied to the Series.
Both methods convert a Pandas Series to a string, but there are differences. astype('str')
specifically converts the Series elements to strings, while apply(str)
applies the str
function to each element, providing more flexibility for custom transformations.
The max_rows
and max_cols
parameters in the to_string
method allow you to control the maximum number of rows and columns displayed in the string representation of the Series, providing flexibility in managing output size.
The float_format
, line_width
, max_colwidth
, and other parameters in the to_string
method provide options for customizing the formatting of floating-point numbers, controlling the line width, setting the maximum column width, and more.
The header
and index
parameters in the to_string
method allow you to include or exclude the header and index, providing control over the appearance of these elements in the string representation.
Conclusion
In this article, I have explained Series.to_string()
function and using its syntax, parameters, and usage how we convert the Pandas Series to String with examples. As well as I explained how to change a Series to a string list using the astype()
function.
Happy learning!!