Home > database >  Iterate over function and concatinate results
Iterate over function and concatinate results

Time:03-26

So let's say I have a function x which I want to iterate over a list of 3 What I wat to do is to iterate over this list and concatinate the results. Like this:

number1 = func(1)
number2 = func(2)
number3 = func(3)

And then

Results = pd.concat([number1, number2, number3], axis = 1)

I tried it like this

numbers = list(range(1:3)
for i in numbers:
  Results = pd.concat([func(i)], axis = 1)

it didn't work...

Anybody have an idea?

CodePudding user response:

You could use list-comprehension and loops like the other answers suggested, or, if func takes only one parameter, you could use map:

df = pd.concat(map(func, range(1, 4)), axis=1)

Example output:

>>> def func(x):
...    return pd.DataFrame({f'col{x}':[x, x, x]},)
    
>>> df = pd.concat(map(func, range(1, 4)), axis=1)
>>> df
   col1  col2  col3
0     1     2     3
1     1     2     3
2     1     2     3

CodePudding user response:

Try this using list comprehension:

results = pd.concat([func(i) for i in range(1,4)], axis=1)

or with a conventional loop:

lst = []
for i in range(1,4):
    lst.append(func(i))
results = pd.concat(lst, axis=1)

This will loop and concatenate func(1), func(2), and func(3). It's important to remember range(a,b) gives the range [a,b) where b is exclusive.

CodePudding user response:

Try list comprehension:

numbers = list(range(1,4))
Results = pd.concat([func(i) for i in numbers], axis=1)

CodePudding user response:

Here are two ways to do it. The first uses a loop as you have hinted at in your question. The second simply uses a list comprehension to call the function repeatedly and use the results to initialize your Results dataframe.

import pandas as pd
def func(i):
    return i / 2
numbers = list(range(1, 4))
Results = pd.DataFrame({'result':[func(i) for i in numbers]})
print('Using list comprehension:')
print(Results)

Results = pd.DataFrame({'result':[]})
for i in numbers:
    Results = pd.concat([Results, pd.DataFrame({'result':[func(i)]})], axis=0)
print('Using concat in a loop:')
print(Results)

Output:

Using list comprehension:
   result
0     0.5
1     1.0
2     1.5
Using concat in a loop:
   result
0     0.5
0     1.0
0     1.5
  • Related