简体   繁体   中英

How to run single function in to a number of times in python

I tried to run simple function n times by using the code below:

 df = pd.DataFrame()

def repeat_fun(times, f, args):
    for i in range(times): f(args)

def f(x):
    g = np.random.normal(0, 1, 32)
    mm = np.random.normal(491.22, 128.23, 32)
    x = 491.22+(0.557*(mm -491.22))+(g*128.23*(np.sqrt(1-0.557**2)))
    print x
repeat_fun(2,f,df)

But I want the result column-wise with respect to run times. The function above gives the result in one array types.Can anyone help me to figure-out this problem.

Hard to know what you mean, but I assume you want the results of f to be stored as columns in a dataframe. If thats's the case:

import pandas as pd
import numpy as np
df = pd.DataFrame()

def repeat_fun(times, f, args):
    for i in range(times): f(i,args)

def f(iteration,df):
    g = np.random.normal(0, 1, 32)
    mm = np.random.normal(491.22, 128.23, 32)
    x = 491.22+(0.557*(mm -491.22))+(g*128.23*(np.sqrt(1-0.557**2)))
    df[iteration] = x

repeat_fun(2,f,df)

Run this and look at/print the contents of df and see if that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM