如何使用 Python(也许 pandas?)来呈现表格数据
How to present tabular data using Python (and maybe pandas?)
我想根据函数和两个列表的乘积创建一个 table(比如在 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
您可以使用将 rows
和 columns
转换为 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
我想根据函数和两个列表的乘积创建一个 table(比如在 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
您可以使用将 rows
和 columns
转换为 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