【问题标题】:python generating excel with pandapython用熊猫生成excel
【发布时间】:2017-08-23 16:33:15
【问题描述】:

让我详细告诉你我的问题...我有一个循环输出我的人名将向我输出该名称,然后我希望将该名称存储在 Excel 工作表(即 DATAFRAME)中,但它始终存储 FOR 循环在最后一次迭代中给出的名称,并且它在先前迭代中输出的所有其他名称都将丢失,肯定是一次又一次地写过这里是我的完整代码,请具体回答

from scipy.spatial import distance
import csv
import dlib
import os
import numpy as np
import cv2
import pandas as pd
from skimage import  io
import face_recognition
from PIL import Image
with open("Data/train.csv","r") as facefeatures2:
    reader=csv.reader(facefeatures2)
    featureslist2=[]
    for row in reader:
        if len(row) != 0:
            featureslist2= featureslist2 +[row]

facefeatures2.close()
float_int2=[]
results=[]
for f2 in range(0,len(featureslist2)):
    float_int2 = float_int2 +[[float(str) for str in subarray] for subarray in [featureslist2[f2]]]
    csv2 = np.vstack(float_int2)
faces_folder_path = "Data/newcropped"
list = os.listdir(faces_folder_path) # dir is your directory path
number_files = len(list)
print (number_files)

writer = pd.ExcelWriter('pandas_name11.xlsx', engine='xlsxwriter')
for loop in range(0,number_files):
    print("iteration ="+str(loop+1))
    unknown_image = face_recognition.load_image_file(faces_folder_path + "/" + str(loop+1)+".jpg")
    cv2.imshow("test",unknown_image)
    cv2.waitKey(0)
    #### --------------exception handling-----------####
    try:
        unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]

    except  IndexError:
        print("--->image is not detectable")
        pass
        # ...........................#
    results = face_recognition.compare_faces(csv2, unknown_face_encoding)
    chunks=[results[x:x + 12] for x in range(0, len(results),12)] # splits "results" list into sublists of size 12
    dirpath = "Data/eachperson"
    fname = []
    fname = [f for f in sorted(os.listdir(dirpath))]
    counter = 0
    index=0
    for c in range (0,len(chunks)):
        if 'True' in str(chunks[c]):
            counter=counter+1
            index=c
            df = pd.DataFrame({'names': [fname[index]]})
            df.to_excel(writer, sheet_name='Sheet1')
    if counter !=1 or counter ==0 :
           print("student is not present :(")
    else:
        print(str(fname[index])+" is present!!!")
writer.save()

【问题讨论】:

标签: python


【解决方案1】:

可以在here 找到一个类似的问题以及可以解决您问题的答案。

编辑:我将尝试在无法测试您的代码的情况下扩展我的答案。

df = pd.DataFrame({'names': [fname[index]]})

在每个循环中覆盖数据帧。

df.to_excel(writer, sheet_name='Sheet1')

将要写入 Excel 的数据框存储在第一页上。在下一次迭代中,您将覆盖此信息。 Pandas 的 to_excel() 函数没有附加。

您可以尝试先将所有名称存储在列表中,转换为数据框,然后再转换为 to_excel()。

names_present = []
for loop in range(0,number_files):
    print("iteration ="+str(loop+1))
    unknown_image = face_recognition.load_image_file(faces_folder_path + "/" + str(loop+1)+".jpg")
    cv2.imshow("test",unknown_image)
    cv2.waitKey(0)
    #### --------------exception handling-----------####
    try:
        unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]

    except  IndexError:
        print("--->image is not detectable")
        pass
        # ...........................#
    results = face_recognition.compare_faces(csv2, unknown_face_encoding)
    chunks=[results[x:x + 12] for x in range(0, len(results),12)] # splits "results" list into sublists of size 12
    dirpath = "Data/eachperson"
    fname = []
    fname = [f for f in sorted(os.listdir(dirpath))]
    counter = 0
    index=0
    for c in range (0,len(chunks)):
        if 'True' in str(chunks[c]):
            counter=counter+1
            index=c
    if counter !=1 or counter ==0 :
           print("student is not present :(")
    else:
        print(str(fname[index])+" is present!!!")
        # Store all names present in list
        names_present.append(str(fname[index])
# Convert list to dataframe and safe
writer = pd.ExcelWriter('pandas_name11.xlsx', engine='xlsxwriter')
df = pd.DataFrame({'names': names_present})
df.to_excel(writer, sheet_name='Sheet1')
writer.save()

【讨论】:

  • silvanoe 现在请回答我的编辑版本谢谢
猜你喜欢
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
  • 2020-02-12
  • 2018-10-14
  • 2017-11-06
  • 2015-03-24
相关资源
最近更新 更多