回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我有一个<code>pandas.DataFrame</code>要导出到CSV文件。然而,pandas似乎将一些值编写为<code>float</code>,而不是<code>int</code>类型。我找不到改变这种行为的方法。</p>
<p>建立数据框架:</p>
<pre><code>df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'], dtype=int)
x = pandas.Series([10,10,10], index=['a','b','d'], dtype=int)
y = pandas.Series([1,5,2,3], index=['a','b','c','d'], dtype=int)
z = pandas.Series([1,2,3,4], index=['a','b','c','d'], dtype=int)
df.loc['x']=x; df.loc['y']=y; df.loc['z']=z
</code></pre>
<p>查看:</p>
<pre><code>>>> df
a b c d
x 10 10 NaN 10
y 1 5 2 3
z 1 2 3 4
</code></pre>
<p>导出它:</p>
<pre><code>>>> df.to_csv('test.csv', sep='\t', na_rep='0', dtype=int)
>>> for l in open('test.csv'): print l.strip('\n')
a b c d
x 10.0 10.0 0 10.0
y 1 5 2 3
z 1 2 3 4
</code></pre>
<p>为什么十位数有一个零点?</p>
<p>当然,我可以将此函数插入我的管道以重新转换整个CSV文件,但似乎没有必要:</p>
<pre><code>def lines_as_integer(path):
handle = open(path)
yield handle.next()
for line in handle:
line = line.split()
label = line[0]
values = map(float, line[1:])
values = map(int, values)
yield label + '\t' + '\t'.join(map(str,values)) + '\n'
handle = open(path_table_int, 'w')
handle.writelines(lines_as_integer(path_table_float))
handle.close()
</code></pre>