首页 > 解决方案 > 不需要的空白导致列失真

问题描述

我正在尝试从间隔的(不是标签式的)txt 文件中导入化学品列表。

在此处输入图像描述

NO FORMULA NAME CAS No A B C D TMIN TMAX code ngas@TMIN ngas@25 C ngas@TMAX
1 CBrClF2 bromochlorodifluoromethane 353-59-3 -0.0799 4.9660E-01 -6.3021E-05 -9.0961E-09 200 1500 2 96.65 142.14 572.33
2 CBrCl2F bromodichlorofluoromethane 353-58-2 4.0684 4.1343E-01 1.6576E-05 -3.4388E-08 200 1500 2 87.14 127.90 545.46
3 CBrCl3 bromotrichloromethane 75-62-7 7.3767 3.5056E-01 6.9163E-05 -4.9571E-08 200 1500 2 79.86 116.73 521.53
4 CBrF3 bromotrifluoromethane 75-63-8 -9.5253 6.5020E-01 -3.4459E-04 1.0987E-07 230 1500 1,2 123.13 156.61 561.26
5 CBr2F2 dibromodifluoromethane 75-61-6 2.8167 4.9405E-01 -1.2627E-05 -2.8629E-08 200 1500 2 100.89 148.24 618.87
6 CBr4 carbon tetrabromide 558-13-4 10.6812 3.2869E-01 1.0739E-04 -6.0788E-08 200 1500 2 80.23 116.62 540.18
7 CClF3 chlorotrifluoromethane 75-72-9 13.8075 4.7487E-01 -1.3368E-04 2.2485E-08 230 1500 1,2 116.23 144.10 501.22
8 CClN cyanogen chloride 506-77-4 0.8665 3.6619E-01 -2.9975E-05 -1.3191E-08 200 1500 2 72.80 107.03 438.19

当我用熊猫导入时

df = pd.read_csv('trial1.txt', sep='\s')

我得到:

在此处输入图像描述

对于前 5 个化合物(索引 0-4),名称在列中是正确的,Name但对于第 6 个(索引 5)和第 8 个(索引 7)化合物 - 它们的名称因空间而被划分,它转到CAS. 随后导致CAS列值位于列和值之下No,依此类推。

有没有办法消除这个问题?谢谢

标签: pythonpandasstringdataframecsv

解决方案


我建议您在将“trial1.txt”文件加载到 df 之前对其进行一些工作。以下代码将导致您最终想要获得的结果:

with open ('trial1.txt') as f:
    l=f.readlines()

l=[i.split() for i in l]
target=len(l[1])
for i in range(1,len(l)):
    if len(l[i])>target:
        l[i][2]=l[i][2]+' '+l[i][3]
        l[i].pop(3)
l=['#'.join(k) for k in l] #supposing that there is no '#' in your entire file, otherwise use some other rare symbol that doesn't eist in your file
l=[i+'\n' for i in l]
 
with open ('trial2.txt', 'w') as f:
    f.writelines(l)

df = pd.read_csv('trial2.txt', sep='#', index_col=0)

推荐阅读