Home > Back-end >  df.columns return the columns with a tuple list not in string list
df.columns return the columns with a tuple list not in string list

Time:08-14

I'm trying to merge 2 df with the same columns name, as always I do df.columns.to_list(), but something weird is happening. Instead of getting the list with the strings of the name of the column I'm getting [('name_column1',), ('name_column2',) ...] I have been 3 days struggling myself, but even renaming once you do the .column still return a tuple.

Thanks very mutch for the help :)

enter image description here

enter image description here

CodePudding user response:

You can loop the column header get first element in tuple

df.columns = [col[0] for col in df.columns]
# or
df.columns = df.columns.get_level_values(0)

CodePudding user response:

It is because your dataframe has multi-indexes. Try:

col_names = [multi_index[0] for multi_index in df.columns.to_list()]
  • Related