How do I properly call a function and return an updated dataframe?

Sedric Hibler

I am trying to process and update rows in a dataframe through a function, and return the dataframe to finish using it. When I try to return the dataframe to the original function call, it returns a series and not the expected column updates. A simple example is below:

df = pd.DataFrame(['adam', 'ed', 'dra','dave','sed','mike'], index =
['a', 'b', 'c', 'd', 'e', 'f'], columns=['A'])

def get_item(data):
    comb=pd.DataFrame()
    comb['Newfield'] = data     #create new columns
    comb['AnotherNewfield'] = 'y'

return pd.DataFrame(comb)

Caling a function using apply:

>>> newdf = df['A'].apply(get_item)

>>> newdf
a          A   Newfield AnotherNewfield
a  adam  st...
b          A   Newfield AnotherNewfield
e   sed  st...
c          A   Newfield AnotherNewfield
d  dave  st...
d          A   Newfield AnotherNewfield
d  dave  st...
e          A   Newfield AnotherNewfield
s   NaN  st...
f         A   Newfield AnotherNewfield
m  NaN  str(...
Name: A, dtype: object
>>> type(newdf)
<class 'pandas.core.series.Series'>

I assume that apply() is bad here, but am not quite sure how I 'should' be updating this dataframe via function otherwise.

Edit: I appologize but i seems I accidentally deleted the sample function on an edit. added it back here as I attempt a few other things I found in other posts.

Testing in a slightly different manner with individual variables - and returning multiple series variables -> seems to work so I will see if this is something I can do in my actual case and update.

def get_item(data):

    value = data     #create new columns
    AnotherNewfield = 'y'
    return pd.Series(value),pd.Series(AnotherNewfield)
df['B'], df['C'] = zip(*df['A'].apply(get_item))
Lukas

You could use groupby with apply to get dataframe from apply call, like this:

import pandas as pd

# add new column B for groupby - we need single group only to do the trick
df = pd.DataFrame(
    {'A':['adam', 'ed', 'dra','dave','sed','mike'], 'B': [1,1,1,1,1,1]},
    index=['a', 'b', 'c', 'd', 'e', 'f'])

def get_item(data):
    # create empty dataframe to be returned
    comb=pd.DataFrame(columns=['Newfield', 'AnotherNewfield'], data=None)
    # append series data (or any data) to dataframe's columns 
    comb['Newfield'] = comb['Newfield'].append(data['A'], ignore_index=True)
    comb['AnotherNewfield'] = 'y'
    # return complete dataframe
    return comb

# use column B for group to get tuple instead of dataframe
newdf = df.groupby('B').apply(get_item)
# after processing the dataframe newdf contains MultiIndex - simply remove the 0-level (index col B with value 1 gained from groupby operation)
newdf.droplevel(0)

Output:

    Newfield    AnotherNewfield
0   adam        y
1   ed          y
2   dra         y
3   dave        y
4   sed         y
5   mike        y

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How do I call a function on a view when the @ObservedObject is updated

From Dev

How do I call a function inside a for loop and write the return on another dataframe column

From Dev

How do I call a nested JavaScript function properly

From Dev

How do I properly call a non-return-value Swift function when it also has an overloading version that has returned value?

From Dev

How do I return function after getting the value in http call?

From Dev

How do I index a function call that return a array (MatLab)?

From Dev

How do I call a function/return a value in VBA?

From Dev

How do I get the updated document back after I call document.save() function in mongoose?

From Dev

How do I specify the return type of a PySpark function as a dataframe?

From Dev

How Can I Call a Function Properly?

From Dev

How do I properly call setters on a return constant referenced class member

From Dev

How do I set a variable then call the updated variable in the same function? PHP

From Dev

How do I properly format this API call?

From Dev

How do I properly use javascript axios .get() function to call get_queryset() function in Django viewset?

From Dev

How do I return a divStr properly?

From Dev

How do I properly return 'this' in Thenable objects?

From Dev

How do I properly modify a cell in a dataframe?

From Dev

Kivy - How do I call trigger_action() in a loop and have it function properly?

From Dev

How do I properly return a CollectionViewCell with reuseIdentifier if weak self is nil in RxDataSource function?

From Dev

How do I make this F# Function properly return a boolean value while using a For In statement?

From Dev

JavaScript: How do I return two values from a function and call those two variables in another function?

From Dev

How can I return a recursive call to a function?

From Dev

How do I properly send the "this" object to a function

From Dev

How do i use timer function properly

From Dev

How can I ensure a reactjs state is updated, and then call a function?

From Dev

How do I call a reducer with a slightly-updated prop value?

From

How do I call the `function` function?

From Dev

how do I call a function in a function in onclick?

From Dev

How do i call a function in a doGet function?

Related Related

  1. 1

    How do I call a function on a view when the @ObservedObject is updated

  2. 2

    How do I call a function inside a for loop and write the return on another dataframe column

  3. 3

    How do I call a nested JavaScript function properly

  4. 4

    How do I properly call a non-return-value Swift function when it also has an overloading version that has returned value?

  5. 5

    How do I return function after getting the value in http call?

  6. 6

    How do I index a function call that return a array (MatLab)?

  7. 7

    How do I call a function/return a value in VBA?

  8. 8

    How do I get the updated document back after I call document.save() function in mongoose?

  9. 9

    How do I specify the return type of a PySpark function as a dataframe?

  10. 10

    How Can I Call a Function Properly?

  11. 11

    How do I properly call setters on a return constant referenced class member

  12. 12

    How do I set a variable then call the updated variable in the same function? PHP

  13. 13

    How do I properly format this API call?

  14. 14

    How do I properly use javascript axios .get() function to call get_queryset() function in Django viewset?

  15. 15

    How do I return a divStr properly?

  16. 16

    How do I properly return 'this' in Thenable objects?

  17. 17

    How do I properly modify a cell in a dataframe?

  18. 18

    Kivy - How do I call trigger_action() in a loop and have it function properly?

  19. 19

    How do I properly return a CollectionViewCell with reuseIdentifier if weak self is nil in RxDataSource function?

  20. 20

    How do I make this F# Function properly return a boolean value while using a For In statement?

  21. 21

    JavaScript: How do I return two values from a function and call those two variables in another function?

  22. 22

    How can I return a recursive call to a function?

  23. 23

    How do I properly send the "this" object to a function

  24. 24

    How do i use timer function properly

  25. 25

    How can I ensure a reactjs state is updated, and then call a function?

  26. 26

    How do I call a reducer with a slightly-updated prop value?

  27. 27

    How do I call the `function` function?

  28. 28

    how do I call a function in a function in onclick?

  29. 29

    How do i call a function in a doGet function?

HotTag

Archive