2017-04-21 37 views
2

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.

回答

1

增加額外的頭之後沒有LEN(),我認爲問題是python 3zip回報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 

如果山坳UMNS有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 
+0

我得到這個錯誤** unhashable類型: 'numpy.ndarray' **後,我添加列表 –

+0

和其他解決方案?什麼返回'print(vals)'? – jezrael

+0

什麼返回'print(df.columns)'? – jezrael