Convert Pandas Series to String

Using pandas.Series.to_string() we can convert a Series to 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 listSeries 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.

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.


# Below are some quick examples 

# 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 : buffer to write to
  • na_rep : string representation of NAN to use, default ‘NaN’
  • float_format : formatter function to apply to columns’ elements if they are floats default None
  • header : It provides Series header (index name)
  • index : Defines index (row) labels, default True
  • length : Represents the Series length
  • dtype : Add the Series dtype
  • name : Add the Series name if not None
  • max_rows : Maximum number of rows

2.2 Return Value

It returns a formatted string.

3. Pandas Conver Series to String using to_string() function

The to_string() function is used to provide a string representation of the given series object which ideally converts Pandas Series to string.

Let’s create Pandas Series,


# create a series
import pandas as pd
ser = pd.Series(["Spark", "PySpark", "Hadoop", "Python", "Pandas"], dtype="string")
print(ser)
print(type(ser))

Yields below output.

pandas series to string
Pandas Series

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(str)
print(type(str))

Yields below output.

convert series to string
Convert Pandas Series to string

3.2 Convert Pandas Series to String without Index

We can also convert Series to string without index using to_string() function. For that we need to set Index param as False into 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(str)

# Output:
#  Spark
# PySpark
#  Hadoop
#  Python
#  Pandas 

In the above example, we have converted a string dtype series to 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 to convert int dtype Series into string object using this function. Create Pandas Series using list of int datatype values and convert those values into string type.

Let’s create Pandas Series,


# create a series with int datatype
ser = pd.Series([22000, 25000, 23000, 24000, 26000], dtype="int64")
print(ser)
print(type(ser))

# Output:
# 0    22000
# 1    25000
# 2    23000
# 3    24000
# 4    26000
# dtype: int64 

Let’s convert it to String.


str = ser.to_string()
print(str)
print(type(str))

# Output:
# 0    22000
# 1    25000
# 2    23000
# 3    24000
# 4    26000

4. Convert Pandas Series to String List

we can convert a Series into a string list using astype() function and 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(str)
print(type(str))

# Output:
# ['Spark', 'Hadoop', 'pandas', 'Python', 'PySpark']

5. Convert Specific Column to String

You can also use Series.astype() to convert a specific column. Since each column on DataFrame is pandas Series, I will get the column from DataFrame as Series and use astype() function to get it as String. In the below example df.Fee or df['Fee'] returns Series object.

Let’s create DataFrame using data from the Pyhton 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

6. Conclusion

In this article, I have explained Series.to_string() function and using its syntax and parameters how to 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!!

Related Articles

References

Vijetha

With 5 of experience in technical writing, I have had the privilege to work with a diverse range of technologies like Python, Pandas, NumPy and R. During this time, I have consistently demonstrated my ability to grasp intricate technical details and transform them into comprehensible materials.

Leave a Reply

You are currently viewing Convert Pandas Series to String