如何在Python 3中透视/交叉制表数据?

3 投票
2 回答
3180 浏览
提问于 2025-04-17 10:44

在Python 3中,如何最好地处理透视表或交叉表?有没有内置的功能可以做到这一点?我希望找到一个不需要外部库的Python 3解决方案。例如,给定一个嵌套列表:

nl = [["apples", 2 "New York"], 
      ["peaches", 6, "New York"],
      ["apples", 6, "New York"],
      ["peaches", 1, "Vermont"]]  

我想能够重新排列行数据并按字段分组:

             apples    peaches
New York        2         6
Vermont         6         1

上面的例子很简单,但有没有比每次想要透视时都使用itertools.groupby更简单的解决方案?理想情况下,这个解决方案应该允许根据任何列来透视行数据。我曾考虑过使用pandas,但它是一个外部库,并且对Python 3的支持有限。

2 个回答

0

itertools.groupby 正是为这个问题而设计的。你很难找到比这个更好的解决方案,尤其是在标准库里面。

1

这里有一些简单的代码。计算行总和、列总和和总计的部分留给读者自己去做。

class CrossTab(object):

    def __init__(
        self,
        missing=0, # what to return for an empty cell.
                   # Alternatives: '', 0.0, None, 'NULL'
        ):
        self.missing = missing
        self.col_key_set = set()
        self.cell_dict = {}
        self.headings_OK = False

    def add_item(self, row_key, col_key, value):
        self.col_key_set.add(col_key)
        try:
            self.cell_dict[row_key][col_key] += value
        except KeyError:
            try:
                self.cell_dict[row_key][col_key] = value
            except KeyError:
                self.cell_dict[row_key] = {col_key: value}

    def _process_headings(self):
        if self.headings_OK:
            return
        self.row_headings = list(sorted(self.cell_dict.keys()))
        self.col_headings = list(sorted(self.col_key_set))
        self.headings_OK = True

    def get_col_headings(self):
        self._process_headings()
        return self.col_headings

    def generate_row_info(self):
        self._process_headings()
        for row_key in self.row_headings:
            row_dict = self.cell_dict[row_key]
            row_vals = [
                row_dict.get(col_key, self.missing)
                for col_key in self.col_headings
                ]
            yield row_key, row_vals

if __name__ == "__main__":

    data = [["apples", 2, "New York"], 
      ["peaches", 6, "New York"],
      ["apples", 6, "New York"],
      ["peaches", 1, "Vermont"]]  

    ctab = CrossTab(missing='uh-oh')
    for s in data:
        ctab.add_item(row_key=s[2], col_key=s[0], value=s[1])
    print()
    print('Column headings:', ctab.get_col_headings())
    for row_heading, row_values in ctab.generate_row_info():
        print(repr(row_heading), row_values)

输出结果:

Column headings: ['apples', 'peaches']
'New York' [8, 6]
'Vermont' ['uh-oh', 1]

另外,您可以查看 这个答案

还有 这个答案,我之前忘记提到它了。

撰写回答