[英]Insert list inside pandas dataframe column names
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'
我收到此错误:
*** 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
我希望list_col_names中的所有项都成为pandas数据帧中的列名
You are effectively passing in ('col_A', 'col_B', ['aa', 'bb'], 'col_C', 'col_D')
as an argument; 你有效地传入
('col_A', 'col_B', ['aa', 'bb'], 'col_C', 'col_D')
作为参数; so for example, try df = pd.DataFrame(columns = ['col_A', 'col_B'] + list_col_names + ['col_C', 'col_D'])
instead. 例如,尝试
df = pd.DataFrame(columns = ['col_A', 'col_B'] + list_col_names + ['col_C', 'col_D'])
。
You got an error because pandas tried to create a single column from a list ['aa', 'bb']
, which doesn't work. 你得到一个错误,因为pandas试图从列表
['aa', 'bb']
创建一个列,但这不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.