python - 将长度为 n 的字符串读取为 pandas 中的 n 列
问题描述
我有.txt
以下格式的文件:
10101011
00101010
11001100
00101101
如何将其作为 n(整数)列的数据框直接读取?IE
0 1 2 3 4 5 6 7
0 1 0 1 0 1 0 1 1
1 0 0 1 0 1 0 1 0
2 1 1 0 0 1 1 0 0
3 0 0 1 0 1 1 0 1
解决方案
一种可能的解决方案是使用read_fwf
带有参数的指定列数widths
:
import pandas as pd
temp = """10101011
00101010
11001100
00101101"""
#after testing replace 'pd.compat.StringIO(temp)' with 'filename.csv'
df = pd.read_fwf(pd.compat.StringIO(temp), header=None, widths= [1] * 8)
print (df)
0 1 2 3 4 5 6 7
0 1 0 1 0 1 0 1 1
1 0 0 1 0 1 0 1 0
2 1 1 0 0 1 1 0 0
3 0 0 1 0 1 1 0 1
推荐阅读
- machine-learning - Colab TPU 错误 - InvalidArgumentError:TPU 不支持的数据类型:double,由输出 cond_8/Merge:0 引起
- javascript - 网站图片上传选择特殊文件夹
- c - C程序将2个整数相加产生异常输出
- mongodb - 如何检索组中任何用户具有特定电子邮件的任何组对象
- python - 如何根据条件删除数据框行
- javascript - TypeScript 抱怨使用 vue-property-decorator 定义的现有 Vue 组件属性
- generics - 如何在 Kotlin 中编写强类型泛型扩展函数?
- c - 由唯一类型限定符组成的声明说明符
- python - 如何创建时间序列的多维数组
- mysql - 如何从订阅列表中获取仅订阅英语频道的用户