数据帧到csv-强制使用相同的分隔符



我有一个浮动值的数据帧(大小:71363 x 7(,我想提取到csv:

df.to_csv('title', sep ='t', header=None, index=False)

然而,由于某些单元格的小数比其他单元格多或少,.csv文件看起来像:

GRID        111163.0    100000.0    7.931   -0.061  1.798   100010.0
GRID        111164.0    100000.0    7.936   -0.057  1.8 100010.0
GRID        111165.0    100000.0    7.893   -0.025  1.781   100010.0
GRID        119347.0    100000.0    7.692   0.631   1.703   100010.0
GRID        119348.0    100000.0    7.686   0.635   1.7 100010.0
GRID        119385.0    100000.0    7.68    0.651   1.698   100010.0

而不是像这样干净的东西

GRID        111163.0    100000.0    7.931   -0.061  1.798   100010.0
GRID        111164.0    100000.0    7.936   -0.057  1.8     100010.0
GRID        111165.0    100000.0    7.893   -0.025  1.781   100010.0
GRID        119347.0    100000.0    7.692   0.631   1.703   100010.0
GRID        119348.0    100000.0    7.686   0.635   1.7     100010.0
GRID        119385.0    100000.0    7.68    0.651   1.698   100010.0

我试图强迫一个";圆形";到我的专栏:

grid_rep_coq[[1,2,3,4,5,6]] = round(grid_rep_coq[[1,2,3,4,5,6]], 3)

但任何小于3位小数的值都不会改变,因此我也有同样的问题。

我找不到任何关于强制使用制表符分隔符的文档。

有人知道怎么做吗?

提前谢谢!

可以使用标准CSV读取器读取数据,其中分隔符设置为空格并启用skipinitialspace

如果你想生成一个结构更好的输出文件,你可以使用一个小助手函数来计算每列的最大宽度,然后将其应用于所有数据项:

import csv
def write_cols(data):
col_spacer = "  "       # added between columns
widths = [max(len(str(item)) for item in row) for row in zip(*data)]
return 'n'.join(col_spacer.join(f"{col:{widths[index]}}" for index, col in enumerate(row)) for row in data)
with open('input.txt', newline='') as f_input:
data = list(csv.reader(f_input, delimiter=' ', skipinitialspace=True))
with open('output.txt', 'w') as f_output:
f_output.write(write_cols(data))

这将为您提供一个output.txt文件,格式为:

GRID  111163.0  100000.0  7.931  -0.061  1.798  100010.0
GRID  111164.0  100000.0  7.936  -0.057  1.8    100010.0
GRID  111165.0  100000.0  7.893  -0.025  1.781  100010.0
GRID  119347.0  100000.0  7.692  0.631   1.703  100010.0
GRID  119348.0  100000.0  7.686  0.635   1.7    100010.0
GRID  119385.0  100000.0  7.68   0.651   1.698  100010.0

熊猫也可以用类似的方式加载:

import pandas as pd
df = pd.read_csv('input.txt', skipinitialspace=True, delimiter=' ', names=['GRID', 'A', 'B', 'C', 'D'], index_col=False)
print(df)

给予:

GRID         A         B      C      D
0  GRID  111163.0  100000.0  7.931 -0.061
1  GRID  111164.0  100000.0  7.936 -0.057
2  GRID  111165.0  100000.0  7.893 -0.025
3  GRID  119347.0  100000.0  7.692  0.631
4  GRID  119348.0  100000.0  7.686  0.635
5  GRID  119385.0  100000.0  7.680  0.651

最新更新