2017-04-15 86 views
1

如何在同一個CSV中打印兩個大熊貓數據框上的不同標題?我嘗試了打印命令,但標題打印在終端而不是CSV。如何在大熊貓數據框上打印標題(.to_csv)

if __name__ == "__main__": 
V = result 
W = reference 
H = np.random.random([5,5100]) 
basis_mat, coef_mat = nmf_nimfa(V, W, H) 

basis_df = pd.DataFrame(data=basis_mat) 
coef_df = pd.DataFrame(data=coef_mat) 

with open('NMF_nimfa.csv', 'w') as f: 
    print "Matrix 1" 
    coef_df.to_csv(f) 
with open('NMF_nimfa.csv', 'a') as f: 
    print "Matrix 1" 
    basis_df.to_csv(f) 

回答

2

如果需要寫入文件與文本新行使用write

with open('NMF_nimfa.csv', 'a') as f: 
    f.write("Matrix 1 \n") 
    coef_df.to_csv(f) 
    f.write("Matrix 1 \n") 
    basis_df.to_csv(f) 
1

如果在調用.to_csv()功能,當你不指定path_or_buf參數 - 它會返回一個字符串。所以,你可以簡單地返回CSV字符串拼接您的標題:

f.write("Matrix 1 \n" + oef_df.to_csv()) 

PS我會建議使用@jezrael's solution鉅額DataFrames作爲我的解決方案可能會導致potentionally爲MemoryError大的DF