pandas.to_csv 输出一列浮点数而不是整数

pandas.to_csv outputs a column of floats instead of integers

我正在从事的项目涉及从数据帧查询数据,对其执行一些操作,然后将其存储在 csv 中。这是精简代码。

get_value() 是一个函数,它 returns 从查询中获得的五个值的平均值,强制转换为 int。

import pandas as pd
d = pd.DataFrame(columns=['"Column1"','"Column2"'])
test = pd.read_csv("./test.csv", header = None, low_memory=False)
for line in range(1, 15):
    if test.values[line][5] == '1':
        value = str(get_value(line, 1))
    else:
        value = str(get_value(line, 0))
    d.loc[line-1]=[line,value]
d.to_csv('output.csv', index = False)

不幸的是,每当我这样做时,我都会将第一列(行,这里显然是一个整数)作为一系列浮点数。示例输出:

1.0,4859
2.0,7882
3.0,10248
4.0,8098
5.0,8048
6.0,6087
7.0,7349
8.0,8246
9.0,5863
10.0,5962
11.0,7641
12.0,8127
13.0,7808
14.0,9886

用 print 语句替换 to_csv 给我一个充满漂亮整数的数据框:

0      1    4859
1      2    7882
2      3   10248
3      4    8098
4      5    8048
5      6    6087
6      7    7349
7      8    8246
8      9    5863
9     10    5962
10    11    7641
11    12    8127
12    13    7808
13    14    9886

因此我怀疑它与to_csv有关,但我是新手,对此还不确定。这是怎么回事,有什么解决方法吗?感谢阅读。

编辑:DSM 有帮助地建议我 运行 d.info()。看来他是对的,而且他们是看起来像 int 的花车。

Int64Index: 14 entries, 0 to 13
Data columns (total 2 columns):
"Id"       14 non-null float64
"Sales"    14 non-null object

您可以通过 'astype' 方法将 'floats' 更改为 'int':

df['id'] =df['id'].astype(int)