2017-04-15 70 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