python - 将具有类似内容的数据框的大字符串转换为数据框
问题描述
所以我有一个文件,我可以通过 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_csv
and read_fwf
,但并没有真正成功。理想情况下,它只会创建一个具有固定列数的数据框(我知道最大列数),如果没有任何值,那么只需创建一个NaN
值。
这可以通过任何方式实现吗?
解决方案
我试过了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'])
这不适用于完整的数据集吗?
推荐阅读
- jenkins - 将文件从远程复制到 Jenkins 工作区
- java - Mongo查询到java
- parsing - Anypoint Studio 中的平面文件(固定宽度)架构创建/解析错误
- google-chrome - 谷歌浏览器不会在控制台中显示错误
- javascript - 如何添加和删除具有选定选项值的类
- django - DJANGO oauth2 grant_type client_credentials
- spotify - 无法从客户端凭证流中搜索轨道使用 access_token
- powershell - 需要使用 PowerShell 从以下代码中的文本文件中读取数组内容
- amazon-web-services - AWS:使用 Route 53 和 S3 存储桶将 www 重定向到 root
- wordpress - 使用 post_excerpt 查询帖子是否存在