错误:“zip”类型的对象在使用zip添加额外标头后没有len()

2024-04-25 18:52:48 发布

您现在位置:Python中文网/ 问答频道 /正文

I try to follow this link pandas dataframe with 2-rows header and export to csv in order for me to created extra header without remove the original header, below is my coding:

df.columns = pd.MultiIndex.from_tuples((zip(df.columns,[uniquevaluesfirstcolumnww, '', uniquevaluesfirstcolumnww1, ' ',uniquevaluesfirstcolumnww2, '  '])))

I get the error such as this: object of type 'zip' has no len()

Anyone have any idea? even though I try to add list before zip but fail also.


Tags: columnsandthetodataframepandasdfwith
1条回答
网友
1楼 · 发布于 2024-04-25 18:52:48

我认为问题在于zip返回object,因此需要转换为list

df.columns = pd.MultiIndex.from_tuples((list(zip(df.columns,[uniquevaluesfirstcolumnww, '', uniquevaluesfirstcolumnww1, ' ',uniquevaluesfirstcolumnww2, '  ']))))

但似乎你需要^{}

^{pr2}$

如果列还有MultiIndex,则:

cols = pd.MultiIndex.from_product([['a','b','c'], ['x','y']])
df = pd.DataFrame([[1,1,1,1,1,1]], columns=cols)
print (df)
   a     b     c   
   x  y  x  y  x  y
0  1  1  1  1  1  1

uniquevaluesfirstcolumnww = 'r'
uniquevaluesfirstcolumnww1 = 's'
uniquevaluesfirstcolumnww2 = 't'
vals = [uniquevaluesfirstcolumnww, '', 
        uniquevaluesfirstcolumnww1, ' ',
        uniquevaluesfirstcolumnww2, '  ']
df.columns = pd.MultiIndex.from_arrays([df.columns.get_level_values(0), 
                                        df.columns.get_level_values(1), 
                                        vals])
print (df)
   a     b     c   
   x  y  x  y  x  y
   r     s     t   
0  1  1  1  1  1  1

相关问题 更多 >

    热门问题