how to convert df.columns to a string in python

To convert the columns of a Pandas DataFrame to a string in Python, you can use the join() function along with a list comprehension. Here's a code snippet that demonstrates this:

main.py
import pandas as pd

# Assume 'df' is the DataFrame
column_string = ', '.join([str(col) for col in df.columns])
print(column_string)
133 chars
6 lines

In this code, we use a list comprehension to iterate over each column name in df.columns, converting each column name to a string using str(col). We then use join() to concatenate all the column names with ', ' as the separator.

Hope this helps!

related categories

gistlibby LogSnag