pandas写入excel,如何不覆盖而是新增行

已有一个号码库(excel),每次输入新号码,检查是否与库中的数据连号(差值小于等于10算连号),并且把新号码添加至号码库中,保存新的excel覆盖原文件,希望能起到一个不断更新库从而比较每次新号码是否连号的效果。但是写出来的代码每次生成excel文件时候,新号码总是覆盖最后一行的数据,而不是在新增行里,行数没有增加。

import pandas as pd
path='newnumber.xlsx'
data=pd.DataFrame(pd.read_excel(io=path,sheet_name=0))
j = len(data)
input_time = 1
for i_new in range(input_time):
    i = int(input('新号码:'))
    for n in range(j):
        if (abs(data['号码库'].loc[n]-i)<=10):
            print('与',data['号码库'].loc[n],'连号')
    data.at[j+1, '号码库'] = i
print(data)
data.to_excel('newnumber.xlsx', index = False)


基于Monster 组和GPT的调写:

在每次添加新号码时,使用append方法可以避免覆盖现有数据。此外,您需要更新变量j以反映新行的数量。

以下是更新的代码:

import pandas as pd

path='newnumber.xlsx'
data=pd.DataFrame(pd.read_excel(io=path,sheet_name=0))
j = len(data)
input_time = 1

for i_new in range(input_time):
    i = int(input('新号码:'))
    for n in range(j):
        if (abs(data['号码库'].loc[n]-i)<=10):
            print('与',data['号码库'].loc[n],'连号')
    data = data.append({'号码库': i}, ignore_index=True)
    j += 1

print(data)
data.to_excel('newnumber.xlsx', index = False)


  • 在新行中使用ignore_index=True参数,可以将新行添加到末尾并忽略索引,从而确保每次添加新号码时都会在新行中进行。