如何使用Python(也许还有pandas?)来呈现表格数据?

问题描述 投票:0回答:2

我想基于一个函数和两个列表的乘积创建一个表格(比如在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)
)

感觉很复杂,我觉得有更好的方法来解决这个问题

python pandas jupyter-notebook tabular
2个回答
3
投票

你要找的是 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

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
© www.soinside.com 2019 - 2024. All rights reserved.