如何在pandas dataframe(.to\u csv)上方打印标题

2024-06-16 10:14:38 发布

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

如何在同一个CSV中打印两个pandas数据帧上方的不同标题?我尝试了打印命令,但标题是在终端打印的,而不是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)

Tags: csv标题dataframedfdatawithbasisrandom
2条回答

{{1}当你调用一个函数时,不要指定一个参数。因此,您可以简单地将标题与返回的CSV字符串连接起来:

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

PS我建议对巨大的数据帧使用@jezrael's solution,因为我的解决方案可能潜在地导致MemoryError的大DFs

如果需要用文本写入新行,请使用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)

相关问题 更多 >