Skip to main content
 首页 » 编程设计

python之如何将 txt 读取为没有符号的数据框

2025年05月04日18zhengyun_ustc

我得到的 txt 文件包含:

[['img_index', 'cent_x', 'cent_y', 's_hum / 12', 'is_skin'], ['1', 1437, 520, 36, 4], ['2', 1363, 488, 36, -1]]

如何在没有'[]'的情况下在pd.Dataframe中打开它

df = pd.read_csv(txt_file) 

我得到了

帮助摆脱

] [ '

请您参考如下方法:

在使用 pandas 读取之前,您需要格式化此文件。


import pandas as pd 
 
 
def transform_csv(line): 
    line = line.replace('[', '') 
    line = line.replace(']]', '') 
    line = line.replace('], ', '\n') 
    line = line.replace("'", '') 
    return line 
 
 
with open("txt_file.txt", "r") as f_in: 
    with open("out.txt", "w") as f_out: 
        for line in f_in: 
            line = transform_csv(line) 
            f_out.write(line) 
        f_out.close() 
    f_in.close() 
 
 
df = pd.read_csv('out.txt') 
print(df) 

输出: