python - 不需要的空白导致列扭曲

标签 python pandas string dataframe csv

我正在尝试从间隔(非制表符)的 txt 文件导入化学品列表。

enter image description here

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

当我用 pandas 导入时

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

我得到:

enter image description here

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

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

最佳答案

我建议您在将“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)

关于python - 不需要的空白导致列扭曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65380200/

相关文章:

java - 如何在java中分割字符串后将其部分存储在字典中

python - 如何正确使用 App Engine Python 模型类的自定义 __init__?

python - 在 Bokeh 中隐藏轴

python - 高效地将值从一列替换为另一列 Pandas DataFrame

python - 为什么 pandas read_csv 发出此警告? (元素比较失败)

swift - 为什么 Swift 接受应该返回元组的代码,但却返回字符串?

c++ - 根据 MSVC++ 中的 unicode 设置自动在 std::string 和 std::wstring 之间切换?

python - 如何在 python 中以内存高效的方式加载和合并多个 .txt 文件?

python - 测试列表和元组中的字符串包含

python - 计算单独列表中 Pandas 列中每个值的出现次数