gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
how to get dataframe column names
- User
how to get dataframe column names
- Assistant
To get the column names of a dataframe, you can use the
columnsattribute of the dataframe. Here's an example:pythonimport pandas as pd # Create a sample dataframe df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) # Get the column names column_names = df.columns # Print the column names print(column_names)Output:
codeIndex(['A', 'B', 'C'], dtype='object')In this example, the
columnsattribute returns an Index object containing the column names. - User
extract column names from index object
- Assistant
To extract the column names from an
Indexobject, you can convert it to a list using thetolist()method. Here's an example:pythonimport pandas as pd # Create a sample dataframe df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) column_names_index = df.columns # Convert Index object to a list column_names = column_names_index.tolist() # Print the column names print(column_names)Output:
code['A', 'B', 'C']In this example, the
tolist()method is applied to theIndexobjectcolumn_names_indexto convert it into a list. The resulting list contains the column names of the dataframe.