首页 > 解决方案 > 如何使用 Python(也许还有 pandas?)呈现表格数据

问题描述

我想根据一个函数和两个列表的乘积创建一个表(比如在 Jupyter 笔记本中)。举一个具体的例子,假设我的数据是:

rows = [1, 2, 3, 4]
columns = [100, 200, 300]
f = x + y

我期待类似的东西

    100 200 300
1   101 201 301
2   102 202 302
3   103 203 303
4   104 204 304

我目前的解决方案是:

import pandas as pd
from itertools import product, zip_longest

# this is from the package more-itertools
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

f = lambda row: row[0] + row[1]
results = (
  pd.DataFrame(grouper(product(rows, columns), len(columns)), columns=columns, index=rows)
 .applymap(f)
)

感觉很复杂,我觉得有更好的方法

标签: pythonpandastabular

解决方案


您正在寻找outer补充。

import pandas as pd
import numpy as np

pd.DataFrame(data=np.add.outer(rows, columns),
             index=rows,
             columns=columns)

   100  200  300
1  101  201  301
2  102  202  302
3  103  203  303
4  104  204  304

推荐阅读