[英]How do I compare adjacent cells in excel using Python?
I have two columns and I am trying to return the total count of rows where both adjacent cells within the two columns are identical. 我有两列,我试图返回两列中相邻单元格相同的行总数。 I am trying to iterate through each row of two columns and compare each item in the first column with its adjacent item in the second column ie 我试图遍历两列的每一行,并将第一列中的每个项目与第二列中的相邻项目进行比较,即
A | B
1 | 1
2 | 3
4 | 4
returns 2 for there are 2 pairs that are identical. 返回2,因为有两对相同。
My two columns are Q and R, so far: 到目前为止,我的两列是Q和R:
import openpyxl
excel_document = openpyxl.load_workbook('example.xlsx')
sheet = excel_document.get_sheet_by_name('Page 1')
created_closed = sheet['Q2':'R1844']
count = 0
for cell in column:
if Q[2] == R[2]: #something along the lines of this
count += 1
import pandas as pd
df = pd.read_excel('example.xlsx')
df = df[df['A'] == df['B']]
print (df.shape[0])
The answer that comes to mind is: 想到的答案是:
count = created_closed[created_closed['Q']==created_closed['R']].shape[0]
No for
loop required because pandas takes care of that. 没有for
循环必需的,因为熊猫需要的照顾。
A - Try using numpy
and pandas
. A - 尝试使用numpy
和pandas
。
1- Find all intersections: This will return an array with the elements that were common in both columns 1-查找所有交叉点:这将返回一个数组,其中包含两列中常见的元素
from pandas import read_excel
import numpy as np
df = read_excel('excel_data.xlsx', names=['A','B'], header=None)
np.intersect1d(df['A'], df['B'])
2- now count the length of the array 2-现在计算数组的长度
B- read each column
and save to, two separate dictionary
with key
being position
and value
being the value
at that position
. B-读取每一column
并保存到两个单独的dictionary
其中key
是position
, value
是该position
的value
。 Compare the two dictionaries
and keep track of matches. 比较两个dictionaries
并跟踪比赛。
something like this, I am traveling right now so I can no test. 像这样的东西,我现在正在旅行,所以我无法测试。
count = 0
col1 = {1:'a', 2:'b', 3:'c'}
col2= {1:'g', 2:'b', 3:'v'}
for key in col1.keys():
if col1[key] == col2[key]:
count = count + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.