擅长:python、mysql、java
<p>如果只想使用<code>numpy</code>:</p>
<pre><code>import numpy as np
mat = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
with open('outfile.txt') as f:
for line in mat:
np.savetxt(f, line, fmt='%.2f')
</code></pre>
<p>然后</p>
<pre><code>cat outfile.txt
1.00 2.00 3.00
4.00 5.00 6.00
7.00 8.00 9.00
</code></pre>
<p>熊猫有<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer">^{<cd2>}</a>方法:</p>
<pre><code>import numpy as np
import pandas as pd
mat = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pd.DataFrame(data=mat.astype(float))
df.to_csv('outfile.csv', sep=' ', header=False, float_format='%.2f', index=False)
</code></pre>
<p>它具有相同的输出:</p>
<pre><code>cat outfile.csv
1.00 2.00 3.00
4.00 5.00 6.00
7.00 8.00 9.00
</code></pre>