gpt4 book ai didi

python - 迭代 Excel 文件,向系列添加列,并使用 Panda 库保存结果

转载 作者:行者123 更新时间:2023-12-01 09:02:35 25 4
gpt4 key购买 nike

使用Python的Panda库,如何迭代Excel文件,向Series添加一列,然后将结果写入文件?下面是我的尝试,但是当我附加到系列时,列会变成行。

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import re

df1 = pd.read_excel('file1.xlsx', sheet_name='Sheet1')
df2 = pd.read_excel('file2.xlsx', sheet_name='Sheet1')
writer = pd.ExcelWriter('Export.xlsx')

for index1, row1 in df1.iterrows():
account1= str(row1['ACCOUNT1'])
not_found = 1
for index2, row2 in df2.iterrows():
account2= str(row2['ACCOUNT2'])
if re.search(account1, account2, re.IGNORECASE):
row1["Results"] = "Found"
not_found = 0
counter+=1
print("found " + counter)
data_writer = row1.append(row1)
break
if not_found ==1:
row1["Results"] = "Found"
counter += 1
print("not found " + counter)
data_writer = row1.append(row1)
data_writer.to_excel(writer,'Sheet1')
writer.save()
print("Finished")

下面是输入文件和预期输出:

enter image description here

enter image description here

最佳答案

我想通了,但我只是希望有一种更短的方法可以在 DataFrame 中附加现有数据,而无需键入所有列。我只想在数据框中添加一个“结果”列来找出匹配的列。

df1 = pd.read_excel('file1.xlsx', sheet_name='Sheet1')
df2 = pd.read_excel('file2.xlsx', sheet_name='Sheet1')
writer = pd.ExcelWriter('Export.xlsx')

counter =0
new_dataframe = pd.DataFrame()
for index1, row1 in df1.iterrows():
account1= str(row1['ACCOUNT1'])
not_found = 1
for index2, row2 in df2.iterrows():
account2= str(row2['ACCOUNT2'])
if re.search(account1, account2, re.IGNORECASE):
not_found = 0
counter+=1
print("found " + str(counter))
new_dataframe = new_dataframe.append(pd.DataFrame({'Results': "Found",
'ACCOUNT1': account1,
'customer':row1['customer'],
'state':row1['state'],
'city':row1['city'] },
index=[0]),
ignore_index=True)
break
if not_found ==1:
counter += 1
print("not found " + str(counter))
new_dataframe = new_dataframe.append(pd.DataFrame({'Results': "Not Found",
'ACCOUNT1': account1,
'customer':row1['customer'],
'state':row1['state'],
'city':row1['city'] }, index=[0]), ignore_index=True)

new_dataframe.to_excel(writer,'Sheet1')
writer.save()
print("Finished")

关于python - 迭代 Excel 文件,向系列添加列,并使用 Panda 库保存结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52357541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com