作者:hk129 | 来源:互联网 | 2023-06-12 09:31
我有一个带for循环的代码,如下所示,它以一些if语句结尾;
def distribution_selection(csv_file=None,product_column=None,demand=None):
out = []
for num in df_all[product_column]:
.
.
.
if best_fit=="norm":
print("Product:",num)
print("Best fit:",best_fit)
print("Likelihood:",likelihoods[best_fit])
print("Parameters:",mean,std)
if best_fit=="nbinom":
print("Product:",p_nbinom,r_binom)
if best_fit=="poisson":
print("Product:",lambda_)
我们说这是结果;
Product: 001.001
Best fit: nbinom
Likelihood: 6.317496035718443e-15
Parameters: 0.002660521439486909 0.41659311972644725
Product: 001.002
Best fit: nbinom
Likelihood: 5.902081129467898e-18
Parameters: 0.005335820123825622 0.7249662663271113
Product: 001.003
Best fit: nbinom
Likelihood: 2.871871246304317e-13
Parameters: 0.00743701201046538 0.45081292375812926
Product: 001.004
Best fit: poisson
Likelihood: 0.0002870492567273848
Parameters: 15.333333333333334
如何使打印输出数据框如下所示?你能帮我这个忙吗?
Products BestFit Likelihood ParameterA ParameterB
001.001 nbinom 6.317496035718443e-15 0.002660521439486909 0.41659311972644725
001.002 nbinom 5.902081129467898e-18 0.005335820123825622 0.7249662663271113
001.003 nbinom 2.871871246304317e-13 0.00743701201046538 0.45081292375812926
001.004 poisson 0.0002870492567273848 15.333333333333334 NA
使用append在循环中创建字典列表,然后传递给DataFrame
构造函数:
df_all = pd.DataFrame({'a':[2,3]})
def distribution_selection(csv_file=None,product_column=None,demand=None):
out = []
#sample data
best_fit = 'norm'
num,mean,std = 1,.03,.05
likelihoods = {'norm':2}
for num in df_all[product_column]:
if best_fit=="norm":
print("Product:",num)
print("Best fit:",best_fit)
print("Likelihood:",likelihoods[best_fit])
print("Parameters:",std)
d = {'Product':num,"Best fit:":best_fit,"Likelihood":likelihoods[best_fit],"Parameters1":mean,"Parameters2":std}
out.append(d)
...
#similar for each conditions
return pd.DataFrame(out)
df = distribution_selection('file','a')
print (df)
Product Best fit: Likelihood Parameters1 Parameters2
0 2 norm 2 0.03 0.05
1 3 norm 2 0.03 0.05