我试图从这段代码获得输出为excel或csv文件。但是由于输出在列表中,我不能这样做。有没有一种方法可以将列表对象转换为dataframe并获得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)
目前,这是我在打印(L)时得到的输出,但我需要将此值存储在excel或csv中作为逐行显示。
发布于 2018-07-23 05:48:36
你可以用你所有的列表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
然后,您可以像以前一样将数据存储在数据框中。
https://stackoverflow.com/questions/51469336
复制相似问题