首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Python (也许还有pandas?)来表示表格数据

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

Stack Overflow用户
提问于 2020-06-18 02:48:27
回答 2查看 40关注 0票数 0

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

代码语言:javascript
复制
rows = [1, 2, 3, 4]
columns = [100, 200, 300]
f = x + y

我希望是这样的

代码语言:javascript
复制
    100 200 300
1   101 201 301
2   102 202 302
3   103 203 303
4   104 204 304

我目前的解决方案是:

代码语言:javascript
复制
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)
)

这感觉非常复杂,我觉得有一种更好的方法

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-18 02:53:13

您正在寻找outer加法。

代码语言:javascript
复制
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
票数 3
EN

Stack Overflow用户

发布于 2020-06-18 02:53:41

您可以使用convert rowscolumns为NumPy数组,并在此处使用broadcasting

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62436240

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档