【发布时间】:2016-09-08 18:11:36
【问题描述】:
首先我想说我不是 Excel 专家,所以我需要一些帮助。
假设我有 3 个 excel 文件:main.xlsx、1.xlsx 和 2.xlsx。在所有这些中,我都有一个名为Serial Numbers 的列。我必须:
- 在
1.xlsx和2.xlsx中查找所有序列号,并验证它们是否在main.xlsx中。
如果找到序列号:
- 在
main.xlsx的最后一列,与找到写入OK + name_of_the_file_in which_it_was_found的序列号 位于同一行。否则,写NOK。同时,如果找到序列号,在最后一栏写上1.xlsx和2.xlsxok或nok。
提及:serial number 可以在 1.xlsx 和 2.xlsx 的不同列中
示例:
main.xlsx
name date serial number phone status
a b abcd c <-- ok,2.xlsx
b c 1234 d <-- ok,1.xlsx
c d 3456 e <-- ok,1.xlsx
d e 4567 f <-- NOK
e f g <-- skip,don't write anything to status column
1.xlsx
name date serial number phone status
a b 1234 c <-- OK (because is find in main)
b c lala d <-- NOK (because not find in main)
c d 3456 e <-- OK (because find main)
d e jjjj f <-- NOK (because not find in main)
e f g <-- skip,don't write anything to status column
2.xlsx
name date serial number phone status
a b c <-- skip,don't write anything to status column
b c abcd d <-- OK (because find main)
c d 4533 e <-- NOK (because not find in main)
d e jjjj f <-- NOK (because not find in main)
e f g <-- skip,don't write anything to status column
现在,我尝试在 Python 中执行此操作,但显然我不知道如何在找到 serial number 的同一行上写入状态列(尝试使用 dataFrames)。任何帮助将非常感激。 (或至少一些指导)
我的问题不是找到重复项,而是跟踪行(在正确的serial number 上写入状态)并在指定列(status 列)写入 excel。
我的尝试:
import pandas as pd
get_main = pd.ExcelFile('main.xlsx')
get_1 = pd.ExcelFile('1.xlsx')
get_2 = pd.ExcelFile('2.xlsx')
sheet1_from_main = get_main.parse(0)
sheet1_from_1 = get_1.parse(0)
sheet1_from_2 = get_2.parse(0)
column_from_main = sheet1_from_main.iloc[:, 2].real
column_from_main_py = []
for x in column_from_main:
column_from_main_py.append(x)
column_from_1 = sheet1_from_1.iloc[:, 2].real
column_from_1_py = []
for y in column_from_1:
column_from_1_py.append(y)
column_from_2 = sheet1_from_2.iloc[:, 2].real
column_2_py = []
for z in column_from_2:
column_2_py.append(z)
建议编辑:
import pandas as pd
get_main = pd.read_excel('main.xls', sheetname=0)
get_1 = pd.read_excel('1.xls', sheetname=0)
get_2 = pd.read_excel('2.xls', sheetname=0)
column_from_main = get_main.ix[:, 'Serial No.'].real
column_from_main_py = column_from_main.tolist()
column_from_1 = get_1.ix[:, 'SERIAL NUMBER'].real
column_from_1_py = column_from_1.tolist()
column_from_2 = get_2.ix[:, 'S/N'].real
column_from_2_py = column_from_2.tolist()
# Tried to put example data at specific column
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
writer = pd.ExcelWriter('first.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
workbook = writer.book
worksheet = writer.sheets['Sheet1']
worksheet.set_column('M:M', None, None)
writer.save()
【问题讨论】:
标签: python excel python-3.x pandas