如何仅将 dataframe.to_csv(...) 中的 float_format 设置为特定列,而不是其他列?

how to set the float_format in dataframe.to_csv(...) only to specific columns, but not others?

我有一个包含 6 列的框架,其中包含 float64 数据。

A B C D E F
  1. 我如何更改数据框以代替 EF uint64?或
  2. 如何告诉 to_csv() 仅打印 EF 的浮点数的整数部分?

尝试使用 .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

to_csv 方法中没有内置选项允许您自定义特定浮点列的格式(至少从版本 0.15.2 开始没有)。只有 float_format 参数影响所有浮动列。

因此,我们可以使用 astype:

更改 EF 列的数据类型
df[['E','F']] = df[['E','F']].astype('uint64')

请注意,这是作业不是 "in-place"。 Python评价右手 首先,生成一个包含两列 dtype uint64 的新 DataFrame,以及 然后将这些值复制到 df。在引擎盖下,Pandas 存储列 不同 "blocks" 中的不同数据类型。 Space 必须分配给块 不同的数据类型;你不能只是拆分现有块的一部分并进行更改 它的数据类型和值。据我所知,没有办法进行更改 就地数据类型。


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