簡體   English   中英

如何使用 Pandas append 一行到一個空的 Dataframe

[英]How do I append a row to an empty Dataframe using Pandas

我正在遍歷 dataframe 中的行,以查看是否在服務器上找不到圖像。 如果未找到,則從 dataframe 中刪除該行並創建一個新的 CSV 文件。 我想將包含在服務器上找不到的圖像和 append 的那一行放到一個新的 dataframe 中,它將創建一個新的 CSV,我們可以調查為什么找不到圖像。 我可以成功地從原始 dataframe 中刪除該行,但是將新行附加到新的 dataframe 會導致運行一次空的 dataframe。 我該如何解決這個問題

filename2 = 'images_not_found.csv'
orders_csv = pd.read_csv(path + filename)
not_found_images = pd.DataFrame()


for index, row in orders_csv.iterrows():
    if not os.path.isfile(row['Image']):
        orders_csv.drop(index, inplace=True)
        not_found_images.append(row, ignore_index=True)

orders_csv.to_csv(path + filename, index=False)
not_found_images.to_csv(path + filename2, index=False)

聽起來可能令人困惑,但是 pandas DataFrame 的append方法不起作用。 您必須將生成的 Dataframe 重新分配給您的變量。

not_found_images = not_found_images.append(row, ignore_index=True)

與列表不同, df.append(new_df)不會 append 內聯,這意味着不會將new_df添加到df 您需要再次定義df

df = df.append(new_df)

在您的代碼中:

not_found_images = not_found_images.append(row, ignore_index=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM