首页 > 解决方案 > 将具有类似内容的数据框的大字符串转换为数据框

问题描述

所以我有一个文件,我可以通过 Python 读取函数打开它,它返回一个大字符串,基本上看起来像一个数据框,但仍然是一个大字符串。例如,它可能看起来像这样:

1609441 test.test1.test3    1/15.34 -1  100 622 669
160441  test.test1.test3    2/11.101    -1  100 140216  177363
16041   test2.test8.test6   2/15.34 -1  100 2791    2346
160441  test.test7.test5    2/15.34 1   100 Bin Any 5   1794    2346
1609441 test4.test4.test4   2/15.34 1   100 E   Any 5   997 0
1642    test4.test3.test1   28.0.101    -1  100 5409155 10357332

如果它是一个真实的数据框,它看起来像:

1609441 test.test1.test3    1/15.34   -1    100   622       669
160441  test.test1.test3    2/11.101  -1    100   140216    177363
16041   test2.test8.test6   2/15.34   -1    100   2791      2346
160441  test.test7.test5    2/15.34   1     100   Bin       A          5    1794    2346
1609441 test4.test4.test4   2/15.34   1     100   E         A          5    997     0
1642    test4.test3.test1   28.0.101  -1    1     155       7332

可以看出,数据变化很大。有些有 10 行不同的数据,有些只有 7 行 - 依此类推。同样,这是一个大文本字符串,我尝试过read_csvand read_fwf,但并没有真正成功。理想情况下,它只会创建一个具有固定列数的数据框(我知道最大列数),如果没有任何值,那么只需创建一个NaN值。

这可以通过任何方式实现吗?

标签: pythonpandasdataframe

解决方案


我试过了read_csv,这看起来很有效:

t = '''1609441 test.test1.test3    1/15.34 -1  100 622 669
160441  test.test1.test3    2/11.101    -1  100 140216  177363
16041   test2.test8.test6   2/15.34 -1  100 2791    2346
160441  test.test7.test5    2/15.34 1   100 Bin Any 5   1794    2346
1609441 test4.test4.test4   2/15.34 1   100 E   Any 5   997 0
1642    test4.test3.test1   28.0.101    -1  100 5409155 10357332'''

with open('test.txt', 'w') as f:
    f.write(t)
    
pd.read_csv('test.txt', delim_whitespace=True, names=['1', '2', '3' ,'4', '5', '6' ,'7' ,'8', '9', '10'])

这不适用于完整的数据集吗?

数据框图片


推荐阅读