首页 > 解决方案 > 将长度为 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

标签: pythonpandasdataframe

解决方案


一种可能的解决方案是使用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

推荐阅读