python - 错误 : object of type 'zip' has no len() after adding extra header by using zip

标签 python django pandas dataframe

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.

最佳答案

我认为问题是 zippython 3 中返回 object,因此需要转换为 list:

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

但是您似乎需要 MultiIndex.from_arrays :

cols = list('abcdef')
df = pd.DataFrame([[1,1,1,1,1,1]], columns=cols)
print (df)
   a  b  c  d  e  f
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, vals])
print (df)
   a  b  c  d  e  f
   r     s     t   
0  1  1  1  1  1  1

如果列也有 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

关于python - 错误 : object of type 'zip' has no len() after adding extra header by using zip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43535594/

相关文章:

python - 如何在 Windows 中编写 Unix 行尾字符?

django - Django 在哪里存储身份验证 super 用户/密码/电子邮件数据?

python - 反转 'about',没有找到参数

python - Pandas 列值替换

python - 连接已旋转的 Dataframe 中的两列

python - 如何将大于 VRAM 大小的数据传递到 GPU 中?

python - 无法使用 Yahoo Fantasy Sports API 查找统计数据

python - sklearn.externals 模块说明

Python - 在 Django 中使用结构解包

json - 将 Pandas Dataframe 转储到多个 json 文件