python - 如何使用 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)
)
感觉很复杂,我觉得有更好的方法
解决方案
您正在寻找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
推荐阅读
- c++ - 为什么我的项目设置在发布模式下会发生冲突?
- javascript - 两个 React 组件中的电子处理事件
- magento2 - Magento 2 // 在类别页面上显示“优惠标签” // Amasty 特别促销
- c# - Blazor onchange 段落
- sockets - 为什么 TCP Socket send() 给出失败的错误代码 58?
- javascript - 如何在没有按钮的情况下检查单选框情况?
- java - 尝试使用滑块在画布上绘图
- python - 在python3 json中按值查找键
- https - 如何使用 Fiddler 将 Rest API 请求从开发服务器重定向到 localhost
- java - 从html java读取时保留特殊字符?