python / excel:如何为列A中所有相同的值添加列B的值
Excel图片1
Excel图像2
请看“Excel Image 1”开始。
我正在使用python拉前两列,并将它们存储在自己的单独的数组中。 我想要做的是添加列B的值,如果列中的值是相同的。 例如,如果列A中的值为“0”,则加上-200和400,并获得200,因为“0”在列A的行1和行2中。
如“Excel Image 2”中所示添加之后,将两个Column的新值存储在各自独立的数组中,以便我可以将它们用于以后的计算。
import xlrd excel = '/Users/Bob/Desktop/' wb1 = xlrd.open_workbook(excel + 'assignment.xlsx') sh1 = wb1.sheet_by_index(0) colA,colB = [],[] for a in range(0,sh1.nrows): colA.append(int(sh1.cell(a,0).value)) colB.append(int(sh1.cell(a,1).value)) print(colA) print(colB) for i in colA: if i == 0: add = colB[0] + colB[1] print(add)
我想要一个在B列中添加这些值的代码,而不pipeA列中给出了多less个相同的值或数目。
电stream输出:
[0, 0, 1, 2, 2, 2, 3, 3, 4, 4] [-200, 400, 30, 600, -70, 10, 20, -90, 40, 40]
预期产出:
[0, 1, 2, 3, 4] [200, 30, 540, 70, 80]
谢谢!
使用itertools.groupby()
:
from itertools import groupby import xlrd excel = '/Users/Bob/Desktop/' wb1 = xlrd.open_workbook(excel + 'assignment.xlsx') sh1 = wb1.sheet_by_index(0) sheet_rows = [sh1.row(r) for r in range(0, sh1.nrows)] groups = groupby(sheet_rows, lambda row: row[1]) key_list = [] sum_list = [] for key, group in groups: key_list.append(key) sum_list.append(sum(group)) print(key_list) print(sum_list)
我会使用row_values方法。 这被称为行号和列号(从零开始)。 例如,要获取列表中的第一行,请执行以下操作:
first_row = sh1.row_values(0) [0.0, -200.0]
切分列表以从特定列中获取值。 如:
sh1.row_values(0)[1] -200.0
我开始跟踪第一列( curr_key
)中的值,并运行给定密钥cum_sum
的累计和。 当密钥更改时,我只是更新追加cum_sum
sum_list
和更新curr_key
和cum_sum
。 最后要做的是追加累计和中的最后一个值。
curr_key = sh1.row_values(0)[0] cum_sum = sh1.row_values(0)[1] sum_list = [] for a in range(1,sh1.nrows): if sh1.row_values(a)[0] == curr_key: cum_sum += sh1.row_values(a)[1] curr_key = sh1.row_values(a)[0] else: sum_list.append(cum_sum) curr_key = sh1.row_values(a)[0] cum_sum = sh1.row_values(a)[1] sum_list.append(cum_sum)
这在sum_list
产生以下sum_list
:
[200.0, 30.0, 540.0, -70.0, 80.0]
顺便说一句,你的第二个文件有70.0,而不是第3行-70.0。
经过一番思考,我意识到一个更好的方法是使用一个字典(类似于@奥斯汀·黑斯廷斯的答案,但没有groupby
)。
key_vals = [x for x in sh1.col_values(0)] int_vals = [y for y in sh1.col_values(1)] sum_list = {} for i,value in enumerate(key_vals): if str(value) not in sum_list: sum_list[str(value)] = int_vals[i] else: sum_list[str(value)] += int_vals[i] for key in sorted(sum_list): print('{}, {}'.format(key, sum_list[key]))
这产生:
0.0, 200.0 1.0, 30.0 2.0, 540.0 3.0, -70.0 4.0, 80.0