Tags
Asked 2 years ago
2 Aug 2021
Views 232
Lance

Lance posted

Pandas - get list df columns names (e.g) in a string

Pandas - get list df columns names (e.g) in a string
jaydeep

jaydeep
answered Jun 23 '23 00:00

To get a list of column names from a Pandas DataFrame and convert them into a string , you can use the df.columns attribute and the join() method. Here's an example:



import pandas as pd

# Create a sample DataFrame
data = {'Column1': [1, 2, 3],
        'Column2': ['A', 'B', 'C'],
        'Column3': [True, False, True]}
df = pd.DataFrame(data)

# Get column names as a list
column_names = df.columns.tolist()

# Convert the list to a string
column_names_string = ', '.join(column_names)

print(column_names_string)


Output:


Column1, Column2, Column3

In the example above, we create a sample DataFrame with three columns. We then use the columns attribute to obtain the column names as a list using df.columns.tolist(). Finally, we use the join() method to concatenate the column names in the list into a single string, separated by commas. The resulting string is printed as Column1, Column2, Column3.
Post Answer