gpt4 book ai didi

python , Pandas : write content of DataFrame into text File

转载 作者:IT老高 更新时间:2023-10-28 20:22:12 29 4
gpt4 key购买 nike

我有这样的 Pandas 数据框

        X    Y  Z    Value 
0 18 55 1 70
1 18 55 2 67
2 18 57 2 75
3 18 58 1 35
4 19 54 2 70

我想将此数据写入如下所示的文本文件:

18 55 1 70   
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70

我尝试过类似的东西

f = open(writePath, 'a')
f.writelines(['\n', str(data['X']), ' ', str(data['Y']), ' ', str(data['Z']), ' ', str(data['Value'])])
f.close()

这是不正确的。如何做到这一点?

最佳答案

您可以使用 np.savetxt并访问 np 属性 .values:

np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')

产量:

18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70

to_csv :

df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep=' ', mode='a')

注意 np.savetxt 你必须传递一个使用附加模式创建的文件句柄。

关于 python , Pandas : write content of DataFrame into text File,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31247198/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com