Sou*_*nak 63 python file pandas
我有像这样的pandas DataFrame
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
Run Code Online (Sandbox Code Playgroud)
我想以这种方式将这些数据写入文本文件,
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
Run Code Online (Sandbox Code Playgroud)
我尝试过类似的东西
f = open(writePath, 'a')
f.writelines(['\n', str(data['X']), ' ', str(data['Y']), ' ', str(data['Z']), ' ', str(data['Value'])])
f.close()
Run Code Online (Sandbox Code Playgroud)
但它不起作用.这该怎么做?
EdC*_*ica 93
您可以使用np.savetxt和访问np属性.values:
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')
Run Code Online (Sandbox Code Playgroud)
收益率:
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
Run Code Online (Sandbox Code Playgroud)
或者to_csv:
df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep=' ', mode='a')
Run Code Online (Sandbox Code Playgroud)
请注意,np.savetxt您必须传递已使用追加模式创建的文件句柄.
Anz*_*zel 24
您可以使用pandas.DataFrame.to_csv() ,并同时设置index和header到False:
In [97]: print df.to_csv(sep=' ', index=False, header=False)
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
Run Code Online (Sandbox Code Playgroud)
pandas.DataFrame.to_csv 可以直接写入文件,有关更多信息,您可以参考上面链接的文档.
joh*_*ger 16
目前最好的方法是使用df.to_string():
with open(writePath, 'a') as f:
dfAsString = df.to_string(header=False, index=False)
f.write(dfAsString)
Run Code Online (Sandbox Code Playgroud)
将输出以下内容
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
Run Code Online (Sandbox Code Playgroud)
此方法还可以让您轻松选择要打印的列columns属性,让您保留列、索引标签(如果需要),并具有用于间距等的其他属性。
小智 13
@AHegde - 要获取制表符分隔的输出,请使用分隔符 sep='\t'。
对于 df.to_csv:
df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep='\t', mode='a')
Run Code Online (Sandbox Code Playgroud)
对于 np.savetxt:
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d', delimiter='\t')
Run Code Online (Sandbox Code Playgroud)
晚到派对:试试这个>
#pd: your pandas dataframe
base_filename = 'Values.txt'
with open(os.path.join(WorkingFolder, base_filename),'w') as outfile:
pd.to_string(outfile)
#Neatly allocate all columns and rows to a .txt file
Run Code Online (Sandbox Code Playgroud)