【问题标题】:Python combine two columns based on keys in the first columnPython根据第一列中的键组合两列
【发布时间】:2018-11-28 02:03:01
【问题描述】:

假设我在一个 excel 文件中有两列,如下所示:

1 1
1 2
2 3
3 4
4 5
5 6
1 3

我的目标是实现两列之间的映射。如果第一列中的值在多行中相同,则在第二列中添加相应的值。所以我的输出应该是这样的:[1:6, 2:3, 3:4, 4:5, 5:6]

逻辑:数字“1”出现在 3 行中,对应的值为 1,2 和 3。因此,键 1 的总值变为 1+2+3=6。

我从一种方法开始,并做到了这一点:

import xlrd
book = xlrd.open_workbook('C:\\Users\\a593977\\Desktop\\ExcelTest.xlsx')
sheet = book.sheet_by_name('Sheet1')
data = [[sheet.cell_value(c, r) for c in range(sheet.nrows)] for r in range(sheet.ncols)]
firstColumn=data[0]
firstColumn=sorted(firstColumn)
secondColumn=data[1]
secondColumn=sorted(secondColumn)
print(list(zip(firstColumn,secondColumn)))

这段代码的输出是:

[(1.0, 1.0), (1.0, 2.0), (1.0, 3.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0), (5.0, 6.0)]

但目标是:[1:6, 2:3, 3:4, 4:5, 5:6]。我该如何继续?

【问题讨论】:

  • 你的问题让熊猫尖叫。你有吗?
  • 我也尝试过使用它。也不能对数据框做太多事情。

标签: python excel list pandas


【解决方案1】:

使用熊猫。试试groupbysumagg

import pandas as pd

df = pd.read_excel('C:\\Users\\a593977\\Desktop\\ExcelTest.xlsx', header=None)
res = (df
      .groupby(df.columns[0], as_index=False, sort=False)[df.columns[1]]
      .sum()
      .astype(str)
      .agg(':'.join, 1)
      .tolist()
)

print(res)
['1:6', '2:3', '3:4', '4:5', '5:6']

【讨论】:

  • 文件“C:\Users\a593977\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\groupby.py”,第 2617 行,在 _get_grouper 中引发 KeyError(gpr) KeyError: 0 这是我得到的错误。有什么想法吗?
  • @Sid 再试一次。
  • 还是一样。请帮忙。
  • @Sid df = pd.read_excel('C:\\Users\\a593977\\Desktop\\ExcelTest.xlsx'); print(df.columns) 显示什么?
  • Index([1, '1.1'], dtype='object') 那么我应该将代码中的 0 替换为 1 吗?
【解决方案2】:

没有 Pandas,从 [(1.0, 1.0), (1.0, 2.0), (1.0, 3.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0), (5.0, 6.0)]{1: 6, 2: 3, 3: 4, 4: 5, 5: 6}

只需要一个Counter(这是一个专门的defaultdict):

from collections import Counter

x = [(1.0, 1.0), (1.0, 2.0), (1.0, 3.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0), (5.0, 6.0)]

sums = Counter()
for key, value in x:
    sums[key] += value

print(sums)

输出是

Counter({1.0: 6.0, 5.0: 6.0, 4.0: 5.0, 3.0: 4.0, 2.0: 3.0})

如果您需要的不是总和,您可以使用defaultdict

【讨论】:

  • “纯python”答案的主要麻烦在于阅读该excel表。祝你好运
  • @coldspeed book = xlrd.open_workbook('file.xlsx'); s = book.sheets()[0]; x = zip(s.col_values(0, 1), s.col_values(1, 1)) 并不麻烦(虽然可以肯定,xlrd 不在标准库中)。无论如何,这两种方法都有效。 :)
【解决方案3】:

您可以使用 Pandas 读取数据,然后使用 f-strings 进行列表解析(在 Python 3.6+ 中可用)。

df = pd.read_excel('file.xlsx', header=None)

df_sum = df.groupby(0, as_index=False)[1].sum()

res = [f'{i}:{j}' for i, j in df_sum.itertuples(index=False)]

['1:6', '2:3', '3:4', '4:5', '5:6']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多