python - 合并函数的输出
问题描述
我使用以下代码以列表的形式创建了一个二进制“表”:
import numpy as np
from itertools import product
x = [i for i in product(range(2), repeat = 9)]
x = np.array(x)
从那里我创建了 3 个函数来计算我想要的概率:
def FPP1(x):
fh_prob = 0.002
trust = 0
for item in x:
if item[0] > 0:
trust = fh_prob
print(trust)
if item[0] == 0:
trust = 1 - fh_prob
print(trust)
def FPP2(x):
fh_prob = 0.002
trust = 0
for item in x:
if item[1] == 1:
trust = fh_prob
print(trust)
if item[1] == 0:
trust = 1 - fh_prob
print(trust)
def FPP3(x):
fh_prob = 0.002
trust = 0
for item in x:
if item[2] == 1:
trust = fh_prob
print(trust)
if item[2] == 0:
trust = 1 - fh_prob
print(trust)
每个函数大约有 512 个输出,我希望将它们存储在一个列表或表格中。沿着 A 列的线是 FPP1,B 列是 FPP2,第 3 列是 FPP3。我不知道如何做到这一点,任何帮助将不胜感激。
解决方案
不要在函数中打印您需要的值,而是创建一个列表并返回它们。例如,对于FPP1
:
def FPP1(x):
fh_prob = 0.002
trust = 0
output = [trust] #list that the function will return
for item in x:
if item[0] > 0:
trust = fh_prob
output.append(trust) #append to the list instead of printing
if item[0] == 0:
trust = 1 - fh_prob
output.append(trust)
return output #return list of values
FPP2
对和进行类似修改后FPP3
,您可以使用以下命令创建所有输出的二维列表:
output = [FPP1(x), FPP2(x), FPP3(x)]
如果你想要一个pandas.DataFrame
,你可以这样做:
output = pd.DataFrame([FPP1(x), FPP2(x), FPP3(x)]).transpose()
>>> output
0 1 2
0 0.000 0.000 0.000
1 0.998 0.998 0.998
2 0.998 0.998 0.998
3 0.998 0.998 0.998
4 0.998 0.998 0.998
.. ... ... ...
508 0.002 0.002 0.002
509 0.002 0.002 0.002
510 0.002 0.002 0.002
511 0.002 0.002 0.002
512 0.002 0.002 0.002
[513 rows x 3 columns]
推荐阅读
- javascript - catcherror 正在捕获空错误 http.get
- java - 尝试更新现有记录时未找到轴突聚合
- amazon-web-services - AWS CloudFront | 失效
- sql - 外键复合主键问题
- postgresql - PostGIS 中的 M 值
- c# - 使用 CefSharp 时屏幕闪烁
- c++ - 如何根据另一个数组中每个元素的排名对数组进行排序(按升序)?
- angular - 将来自 Spring Boot API 的数据显示到 Primeng 图表 Angular 中
- timestamp - 有没有办法在 Apache Phoenix 中使用 TIME ZONE 信息来更新 TIMESTAMP?
- c - C、传值,在Linux中