使用Python的Panda库,如何遍历excel文件,向Series添加一列,然后将结果写入文件?下面是我的尝试,但是当我添加到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")
下面是输入文件和预期的输出:
答案 0 :(得分:1)
我知道了,但是我只是希望有一种较短的方法,可以在不键入所有列的情况下将现有数据追加到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")