【发布时间】:2020-06-17 18:48:26
【问题描述】:
我想根据一个函数和两个列表的乘积创建一个表(比如在 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)
)
感觉很复杂,我觉得有更好的方法来做到这一点
【问题讨论】:
-
删除了
jupyter-notebook标签,因为它与问题无关。