Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将长度为n的字符串读取为pandas中的n列_Python_Pandas_Dataframe - Fatal编程技术网

Python 将长度为n的字符串读取为pandas中的n列

Python 将长度为n的字符串读取为pandas中的n列,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个.txt文件,格式如下: 10101011 00101010 11001100 00101101 如何将其作为n(整数)列的数据帧直接读取?i、 e 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 一种可能的解决方案是使用参数宽度指定列数: import pandas as

我有一个
.txt
文件,格式如下:

10101011
00101010
11001100
00101101
如何将其作为n(整数)列的数据帧直接读取?i、 e

   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

一种可能的解决方案是使用参数
宽度指定列数:

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

你可以用一个简单的列表来理解

import pandas as pd

text = """10101011
00101010
11001100
00101101"""

df = pd.DataFrame(list(line) for line in text.split('\n'))

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
使用:

将熊猫作为pd导入
df=pd.DataFrame.from_记录(temp.split())
>>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

fwf是一个不错的选择,使用宽度可以让它变得完美。添加
names=['col0','col1','col2','col3','col4','col5','col6','col7']
将负责给出列名