【问题标题】:How to present tabular data using Python (and maybe pandas?)如何使用 Python(也许还有 pandas?)呈现表格数据
【发布时间】: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标签,因为它与问题无关。

标签: python pandas tabular


【解决方案1】:

您正在寻找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

【讨论】:

  • 您在答案中附加了旧文档链接,这里是 v.1.18 链接numpy.ufunc.outer。不错的答案+1
【解决方案2】:

您可以使用将rowscolumns 转换为NumPy 数组并在此处使用broadcasting

rows = np.array([1, 2, 3, 4])
columns = np.array([100, 200, 300])

data = rows[:,None] + columns

df = pd.DataFrame(data,columns= columns,index=rows)
df
   100  200  300
1  101  201  301
2  102  202  302
3  103  203  303
4  104  204  304

【讨论】:

    猜你喜欢
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 2021-02-01
    • 2018-06-06
    • 1970-01-01
    • 2021-01-24
    • 2017-06-17
    相关资源
    最近更新 更多