【问题标题】:Updating python excel data in an existing dataframe在现有数据框中更新 python excel 数据
【发布时间】:2017-08-21 22:58:08
【问题描述】:

我实际上是 python 的新手,目前我正面临熊猫数据框的问题......我有一个循环,它在某些条件下输出我每次迭代中的人/文件夹的名称,我希望这个输出名称立即发送到数据帧,但我在数据帧中得到的只有 1 行具有最后一次迭代的输出,并且所有先前的迭代输出都被写入... 下面是我正在使用的代码 我希望你能理解我的问题并提供帮助

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 pandas dataframe


    【解决方案1】:

    为什么不初始化一个数据框列表?继续追加到列表中,并且仅在最后,您应该将其合并到一个大数据帧中并写入它。 .to_excel 每次写入时都会覆盖 excel 文件,因此在循环中调用它不是一个好主意,除非您以附加模式打开它。但同样,这是低效的。

    试试这样的:

    df_list = []
    for loop in range(0, number_files):
       ...
    
       for c in range (0,len(chunks)):
            if 'True' in str(chunks[c]):
                ...
    
                df_list.append(pd.DataFrame({'names': [fname[index]]}))
    
    writer = pd.ExcelWriter('pandas_name11.xlsx', engine='xlsxwriter')
    pd.concat(df_list).reset_index(drop=True).to_excel(writer, sheet_name='Sheet1')
    

    如果您想在每次迭代中重写,您也可以考虑查看this

    【讨论】:

    • 非常感谢它的工作原理,但它总是在数据框中有一列一直写为 0 !你能告诉我为什么吗?
    • @hamzayahya 不能说没有看到你的数据。如果不是什么大问题,只需在 MS Excel 中打开并删除即可。无论如何,如果有帮助,您可以将此答案标记为已接受。干杯。
    • 兄弟,它只是看起来令人毛骨悚然,为什么我要问它实际上看起来像 [0 john present] 然后在下一行又像 [0 pattrick present] 我希望你明白......
    • 还有什么方法可以让代码在每行前面针对每个名称自动生成日期和时间(即创建时)
    • @hamzayahya 试试这个:pd.concat(df_list).reset_index(drop=True).to_excel(writer, sheet_name='Sheet1')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 2021-05-11
    • 2021-09-08
    • 1970-01-01
    • 2021-03-01
    相关资源
    最近更新 更多