csv文件在浮点数写入时给出字符串

时间:2017-10-18 09:17:42

标签: python csv casting

我的csv文件如下:

"(-0.16192019, -0.007456851, 0.08841695)","(-0.10439591, 0.024501082, 0.12783173)","(-0.05965481, 0.049002163, 0.12144014)",...

但我不想要报价。

我把这个函数写成:

for j in range(len(sensor_data)):
    with open(names[j] + "P" + str(i) + ".csv", "wb") as f:
        writer = csv.writer(f)
        writer.writerows(sensor_data[j])

我的sensor_data[j]是这样的:

gyro.append((float(merge.iloc[j, 2]), float(merge.iloc[j, 3]), float(merge.iloc[j, 4]))) if merge.iloc[j, 0] == 'Gyroscope' \
             else acc.append((float(merge.iloc[j, 2]), float(merge.iloc[j, 3]), float(merge.iloc[j, 4])))

为什么不打印浮点数元组而不是字符串元组?

merge = pd.read_csv(final_user_study_path + "/P" + str(i) + "/DataCollection/data/merge.csv")

合并看起来像:

Gyroscope,50958,-0.3387541,0.014913702,0.05965481
Gyroscope,50978,-0.23009712,0.03621899,0.044741105
LinearAcceleration,50979,-0.09891046,0.119261175,-0.108936176
Gyroscope,50998,-0.1768339,0.066046394,0.040480047
LinearAcceleration,50999,-0.0863409,0.18240824,-0.07152677

所有这些值的类型都是字符串。

我想:

(-0.16192019, -0.007456851, 0.08841695),(-0.10439591, 0.024501082, 0.12783173),(-0.05965481, 0.049002163, 0.12144014),...

1 个答案:

答案 0 :(得分:1)

要阻止csv.writer()在需要时添加引号(因为它发现了单元格中的分隔符),请添加quoting参数,如下所示:

writer = csv.writer(f, quoting=csv.QUOTE_NONE)

请参阅CSV文档:csv.QUOTE_NONE

最好解开元组,这样每个元组都能正确获得自己的单元格,而不需要任何额外的括号。这可以使用itertools.chain.from_iterable()完成,将所有元组折叠为单个列表。例如:

from itertools import chain

row = [(-0.16192019, -0.007456851, 0.08841695), (-0.10439591, 0.024501082, 0.12783173), (-0.05965481, 0.049002163, 0.12144014)]

print row
print list(chain.from_iterable(row))

这会显示:

[(-0.16192019, -0.007456851, 0.08841695), (-0.10439591, 0.024501082, 0.12783173), (-0.05965481, 0.049002163, 0.12144014)]
[-0.16192019, -0.007456851, 0.08841695, -0.10439591, 0.024501082, 0.12783173, -0.05965481, 0.049002163, 0.12144014]

如您所见,第二行显示所有元组已被展平为一个列表。