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']
将负责给出列名