Call a function with values in another dataframe

Question:

I defined a function

def test_function(id):
.....
.....
.....

I was calling that function via

df = test_function('123')

but what I want to do now is, I have another Dataframe df2 =

values
123
354
645
456
176

I want to write an apply function which would take 1 value at a time from df2
and run my test_function instead of manually adding values.

and also my df should be appended for different values,
such that df contain a column name ‘value’ which would be the value selected one at a time

Asked By: Shubham R

||

Answers:

I think you need apply with DataFrame.values and last concat:

Notice: [] are necessary, because pandas function Series.values – so df2.values return numpy array and df2['values'] select column values. Same problem is with another column names with same names as some functions in pandas like count, size, sum

a = f2['values'].apply(test_function).values
print (pd.concat(a, ignore_index=True))
Answered By: jezrael

No need to call this function everytime, instead you do this:

df = pd.DataFrame(columns=['Val'])
df['Val']=list(df2['values'])
Answered By: Chandan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.