How to unpack a DataFrame into separate Series in a function call?

Viewed 241

I have a function that expects several pandas Series as arguments:

def func(s1, s2, s3): 
    print(s1, s2, s3)

And a DataFrame df with columns 'A' through 'Z'.

I would like to call the function like this:

func(*df[['A', 'D', 'R']])

But it appears that unpacking a DataFrame produces just the column names, not the data. I know that Using the double star I can get the three desired series in a dictionary, but then the names have to match, so that doesn't work here.

Is there a concise syntax for what I want to do?

Bonus question: does the python community call the * and ** splat and double-splat? This is a very difficult topic to search for!

3 Answers

I think about the most concise you can get here is

func(*[df[c] for c in "ADR"])

If you don't want the index, you can do:

func(*df[['A', 'D', 'R']].T.values)

T is taking tranpose because otherwise it will be sent row-by-row not column-by-column.

Using df.get under map , we can unpack the subset to individual series:

cols = ['A','D','R']
func(*map(df.get,cols))

Sample Run:

df = pd.DataFrame({"A":[1,2],"B":[3,4],"C":[4,5]})

def func(s1, s2, s3): 
    print(s1, s2, s3)

cols = ['A','B','C']
func(*map(df.get,cols))

0    1
1    2
Name: A, dtype: int64 0    3
1    4
Name: B, dtype: int64 0    4
1    5
Name: C, dtype: int64
Related