2015-02-11 18 views

回答

0

沒有內置到to_csv方法,它允許您自定義格式特別浮動列(至少不爲0.15.2版本)選項。只有影響所有浮點列的參數float_format

因此,相反,我們可以改變使用astypeEF列D型:

df[['E','F']] = df[['E','F']].astype('uint64') 

注意,這是分配不是「就地」。 Python先評估右側 一側,然後用兩列dtype uint64和 生成一個新的DataFrame,然後將這些值複製到df。在引擎蓋下,Pandas在不同的「塊」中存儲不同dtype列的 。空間必須分配給 不同dtype的塊;你不能只是分割現有塊的一部分,並改變它的dtype和values。所以就我所知,沒有辦法在原地執行dtype的更改 。


import pandas as pd 
import numpy as np 

df = pd.DataFrame(np.random.random((3,6))*100, columns=list('ABCDEF')) 
df[['E','F']] = df[['E','F']].astype('uint64') 
df.to_csv('/tmp/out') 

寫入/tmp/out內容像

,A,B,C,D,E,F 
0,80.81297403001469,19.445657677067153,12.108345468895742,61.25250634077517,37,85 
1,51.109960070270176,71.1000927186083,13.221739366008457,64.20402135661978,19,60 
2,27.114372274697264,0.44017074777940035,21.090083439236174,86.57480550319143,79,98 
0

嘗試使用.astype()方法。

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.astype.html

import numpy as np 
import pandas as pd 

df = pd.DataFrame({'sample': np.random.choice([1, 2], 100, replace=True), 
        'x': np.random.uniform(size=100), 
        'y': np.random.normal(size=100), 
        'z': np.random.choice([1,5,7,3,9],100, replace=True)}) 
#Creates this DF 
    sample   x   y 
0  1 0.249924 0.565061 
1  1 0.707201 0.626478 
2  2 0.897220 -1.103307 
3  2 0.818712 -0.924300 
4  1 0.374754 3.138215 
5  2 0.979895 -2.722585 
6  1 0.193894 -0.419265 
7  1 0.675562 -1.835672 
8  2 0.582984 -0.304816 
9  2 0.347588 0.406904 
10  1 0.053714 -0.252964 
11  2 0.709975 -0.412066 
12  1 0.495868 -1.173759 
13  1 0.605189 0.830502 
14  1 0.973732 0.109461 
15  1 0.389914 0.144190 
16  2 0.030194 -1.413897 
17  2 0.554663 -2.613892 
18  2 0.644484 -0.165491 
19  2 0.991261 -0.711845 
#Writes Integer CSV 
df.applymap(lambda x: x.astype(int)).to_csv('mycsv.csv') 

    sample x y 
0  1 0 0 
1  1 0 0 
2  2 0 -1 
3  2 0 0 
4  1 0 3 
5  2 0 -2 
6  1 0 0 
7  1 0 -1 
8  2 0 0 
9  2 0 0 
10  1 0 0 
11  2 0 0 
12  1 0 -1 
13  1 0 0 
14  1 0 0 
15  1 0 0 
16  2 0 -1 
17  2 0 -2 
18  2 0 0 
19  2 0 0 
+0

所以你的意思,把我的數據幀的列EF,得到.astype(UINT64)拷貝數據框中,然後可能被複製取代EF ,然後to_csv() – MMM 2015-02-11 20:06:42

+0

請參閱編輯/ 執行此操作:df.applymap(lambda x:x.astype(int))。to_csv('mycsv.csv') – 2015-02-11 20:16:28

相關問題