Python提取TXT数据转化为DataFrame

第一步:读取文本,open函数

第二步:处理文本,split函数

第三步:利用Numpy, pandas

import pandas as pd
import numpy as np
#打开txt文件
file_object=open("D:/test.txt")
try:
    file_content=file_object.read()
finally:
    file_object.close()
#利用逗号分隔
result=file_content.split(',')
#建立空的list存数据
a=[]
#依次读取
for i in result:
    a.append(i)
#将里面数字变成int
a=list(map(int,a))
#将其变成array
a=np.array(a)
#重组数据变成你想要的矩阵, 60*10
MAT=a.reshape((60,10))
#输出为excel
pd.Dataframe(MAT).to_excel("D:/处理过的txt.xlsx")

数据集(复制粘贴到txt文件练习即可):

0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,145 ,169 ,255 ,255 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,255 ,0 ,0
 ,0 ,205 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,227 ,0 ,0 ,158 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0
 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,150 ,0 ,0 ,0 ,0 ,0 ,0 ,152 ,0 ,0 ,0 ,144
 ,0 ,139 ,0 ,148 ,0 ,0 ,0 ,0 ,0 ,153 ,0 ,0 ,148 ,0 ,0 ,0 ,0 ,0 ,154 ,0 ,0 ,0 ,0 ,58 ,156 ,0 ,0 ,0
 ,0 ,0 ,150 ,0 ,0 ,0 ,0 ,0 ,154 ,153 ,0 ,0 ,219 ,0 ,0 ,0 ,144 ,153 ,158 ,149 ,153 ,0 ,0 ,0
 ,150 ,148 ,0 ,0 ,0 ,154 ,143 ,0 ,145 ,0 ,152 ,0 ,154 ,148 ,153 ,162 ,148 ,155 ,146 ,0
 ,144 ,0 ,152 ,145 ,154 ,0 ,0 ,0 ,0 ,151 ,153 ,148 ,153 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