我正在尝试从此代码中以excel或csv文件的形式输出。但是由于输出在列表中,因此我无法执行。有没有一种方法可以将列表对象转换为数据框并在excel或csv中获取值?
df1 = pd.read_excel('Training.xls') # get input from excel files
df2 = pd.read_excel('Newsss.xlsx') #comparing them
info = df2.shape
totalRow = info[0]
print(totalRow)
for r in range (0,totalRow):
lst = df2.iloc[r,:]
x=df1.iloc[r,1]
cnt = 0
l = []
for i in lst:
if cnt==0:
l.append(i)
cnt=1
continue
elif (i-x)==0:
l.append(1) # condition for my program to work on excel files
elif abs(i-x) > 0.2:
l.append(0)
else:
l.append(i)
print(l)
目前这是我在print(l)时获得的输出,但我需要将此值存储在excel或csv中,按行排列,
答案 0 :(得分:0)
您可以创建一个包含所有列表l
的矩阵,然后转换为数据框以将其写入csv:
# Big matrix with all your lists
m = []
for r in range (0,totalRow):
lst = df2.iloc[r,:]
x=df1.iloc[r,1]
cnt = 0
l = []
for i in lst:
if cnt==0:
l.append(i)
cnt=1
continue
elif (i-x)==0:
l.append(1) # condition for my program to work on excel files
elif abs(i-x) > 0.2:
l.append(0)
else:
l.append(i)
# Append your new list to the matrix
m.append(l)
# Create the data frame
df = pd.DataFrame(m)
# If you have the columns names you may create the df this way
# If the columns names are the same of df1:
columns_names = df1.columns
df = pd.DataFrame(m, columns = columns_names)
file_name = "your_file_name.csv"
df.to_csv(file_name, m)
# You can add a separator like ',', '\t', ';' ...
# df.to_csv(file_name, m, sep = ',')
如果必须转置矩阵,可以执行以下操作:
import numpy as np
# Create a matrix object
m = np.matrix(m)
# Transpose your matrix
m = m.T
比以前您可以将数据存储在数据框中。