Using pandas.Series.to_string() we can convert a single series into a string.Let’s take some examples and see how it’s gonna work.
Create a pandas Series using string dtype data, then convert it to a string.
# create a series ds = pd.Series(["a", "b", "c", "a"], dtype="string") print(ds) # display series s = ds.to_string() # convert to string print() print(repr(s)) display converted output
The variable ds holds a pandas Series with all string data by defining dtype as a string. Then convert the series into a string by using the pandas.Series.to_string method, here we define it as ds.to_string(). Finally, the converted string is assigned to the s variable. And displayed output (variable s) by using the repr() function to return printable representational string.
0 a 1 b 2 c 3 a dtype: string '0 a\n1 b\n2 c\n3 a'
The first part of the above block represents the output of a series with dtype is a string, and the second part of the block represents the converted string output of a single pandas series.
In the above example, we converted a string dtype series to string, but we can convert series with any dtype. Let's take another example.
ds = pd.Series([1,2,3,3]) print(ds) s = ds.to_string() print() print(repr(s))
In this example, it has only integer type data present in the pandas series. For that, directly declare a list of integers to the pd.Series() method and it will create a pandas Series. After that, convert the Series “ds” to string by using ds.to_string() method.
0 1 1 2 2 3 3 3 dtype: int64 '0 1\n1 2\n2 3\n3 3'
We can see the converted string from a single Series with int64 dtype data in the above block. Like this, we can concrete a single series into a string by using the pandas to_string method.