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
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))
No need to call this function everytime, instead you do this:
df = pd.DataFrame(columns=['Val'])
df['Val']=list(df2['values'])
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
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))
No need to call this function everytime, instead you do this:
df = pd.DataFrame(columns=['Val'])
df['Val']=list(df2['values'])