I have a dataframe that I initiate like this:
df = pd.DatFrame(columns=('col_A', 'col_B', 'col_C', 'col_D'))
I want to insert a list of column names in this dataframe, but this does not work:
list_col_names = ['aa', 'bb']
df = pd.DatFrame(columns=('col_A', 'col_B', list_col_names, 'col_C', 'col_D'))
I get this error: *** TypeError: unhashable type: 'list'
How do I fix it? I want all the items in list_col_names to become column names in the pandas dataframe
You are effectively passing in ('col_A', 'col_B', ['aa', 'bb'], 'col_C', 'col_D')
as an argument; so for example, try df = pd.DataFrame(columns = ['col_A', 'col_B'] + list_col_names + ['col_C', 'col_D'])
instead.
You got an error because pandas tried to create a single column from a list ['aa', 'bb']
, which doesn't work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.