How to convert a column in text/string output in Python

pandas is one of the best libraries for data analysis and data manipulation. It is interestingly simple to use and very powerful when working with data. It is particularly helpful when we need to convert a DataFrame to a text/string output that can be printed to the console.

To do that, we use the to_string() method or to_csv() method, which is part of the pandas documentation, to convert a column in our pandas DataFrame to a text of string output in Python.

Using to_string()

When using this method, the DataFrame is rendered to a console-friendly tabular output.

This method has a large number of parameters, such as col_space, header, index, index_names, max_rows, max_cols, and many more.

Code example

import pandas as pd
# create a dataframe
df = pd.DataFrame({'name': ['John', 'Doe', 'Sam', 'Joel'],
'age': [18, 10, 15, 32],
'sex': ['Male', 'Female', 'Female', 'Male']
})
# print the sample dataframe
print(df)
# convert the 'name' column and convert it to a
#string using to_string()
name = df['name'].to_string(index=False)
# print the string on the console
print("Printing string...")
print(name)

Explanation

  • Line 1: We import pandas with an alias pd.

  • Line 4: We create a sample DataFrame with three columns (name, age, and sex).

  • Line 10: We print the DataFrame.

  • Line 14: We declare a variable name and convert the name column in our DataFrame to a string using the .to_string() method and a parameter index which is set to False. This means we want to exclude the row index from the output.

  • Line 17: A print statement.

  • Line 18: We print the string output of the column.

Using to_csv()

A different option is to use the .to_csv() method to write the column to a CSV file and then use the .read_csv() method with the squeeze=True parameter to read the file and turn it into a pandas series.

One parameter, the axis, is required by the squeeze() method (0 for index, 1 for columns); by default, it is None. Its task is to squeeze objects with a single axis into scalars.

Coding example

import pandas as pd
# create a dataframe
df = pd.DataFrame({'name': ['John', 'Doe', 'Sam', 'Joel'],
'age': [18, 10, 15, 32],
'sex': ['Male', 'Female', 'Female', 'Male']
})
# select the 'name' column and write it to a CSV file
df['name'].to_csv('names.csv', index=False)
# read the CSV file and convert it to a pandas
# Series using read_csv() with `squeeze=True`
name_str = pd.read_csv('names.csv', squeeze=True)
# print the series on the console
print(name_str)

Explanation

  • Line 1: We import pandas with an alias pd.

  • Line 4: We create a sample DataFrame with three columns (name, age, and sex).

  • Line 10: We select the name column and write it to a CSV file using the .to_csv() method.

  • Line 14: We read the generated CSV file and convert it to a pandas series with the parameter squeeze set to True.

  • Line 17: We print the string output.

These are the two methods that can be used to convert a column in text output in Python.

Writing the text output to a txt file

After converting the column to text, we may want to write the text to a file, such as a .txt file, and that can be done in the following way:

import pandas as pd
# create a dataframe
df = pd.DataFrame({'name': ['John', 'Doe', 'Sam', 'Joel'],
'age': [18, 10, 15, 32],
'sex': ['Male', 'Female', 'Female', 'Male']
})
# convert the 'name' column and convert it to a
#string using to_string()
name = df['name'].to_string(index=False)
# file object
wtb =open('names.txt','w')
# write to file.
wtb.write(name)
# close the file.
wtb.close()

The code above gets the names in the DataFrame, converts them to a text output using the .to_string() method, and writes the text to a .txt file (names.txt).

We get a succeeded message because the code worked successfully and the column has been saved to the names.txt file.

Conclusion

In this Answer, we explored two methods to convert a column in the pandas DataFrame to a text or string output and print it to the console using the .to_string() method and the .to_csv() method.

Learn more about pandas from Educative's interactive course.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved