我想在每次代碼執行時將資料框添加到 excel 中,在作業表中可用的最后一行。這是我正在使用的代碼:
import pandas as pd
import pandas
from openpyxl import load_workbook
def append_df_to_excel(df, excel_path):
df_excel = pd.read_excel(excel_path)
result = pd.concat([df_excel, df], ignore_index=True)
result.to_excel(excel_path)
data_set1 = {
'Name': ['Rohit', 'Mohit'],
'Roll no': ['01', '02'],
'maths': ['93', '63']}
df1 = pd.DataFrame(data_set1)
append_df_to_excel(df1, r'C:\Users\kashk\OneDrive\Documents\ScreenStocks.xlsx')
我想要的輸出(運行 3 次代碼后):
Rohit 1 93
Mohit 2 63
Rohit 1 93
Mohit 2 63
Rohit 1 93
Mohit 2 63
但我得到的是:
Unnamed: 0.1 Unnamed: 0 Name Roll no maths
0 0 0 Rohit 1 93
1 1 1 Mohit 2 63
2 2 Rohit 1 93
3 3 Mohit 2 63
4 Rohit 1 93
5 Mohit 2 63
不知道我哪里出錯了。
uj5u.com熱心網友回復:
發生這種情況是因為在默認情況下,這些函式像to_excelor to_csv(and etc.) 會添加一個帶有索引的新列。因此,每次保存檔案時,它都會添加一個新列。這就是為什么您應該更改將資料框保存到檔案的原始資料。
result.to_excel(excel_path, index=False)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450710.html
上一篇:將熊貓資料框值插入特定列
下一篇:基于布林值的累積和
