3

I have a function called ReturnDateRange which will return two dates. I am trying to apply this function on a column called 'zRow' in a dataFrame, and store the result in two different columns.

The below will store both results, as a tuple in one column:

df['t1']= df['zRow'].map(ReturnDateRange)

The following returns a ValueError: Too many values to unpack (expected 2)

df['t1'], df['t2']= df['zRow'].map(ReturnDateRange)

But the function always returns two dates, or a single None.

UPDATE: I tried returning two zeros instead of None. Still get the same error.

Thanks for the help.

Kelaref
  • 547
  • 1
  • 8
  • 26

1 Answers1

5

The "Too many values to unpack" error is because its unpacking the rows, rather than columns. Thus a transpose will help, but I feel like there's a nicer way to fix this.

In the mean time, this works, if not very elegantly...

import pandas as pd
import numpy as np

data = pd.DataFrame(np.zeros(shape=(5,2)),columns=["a","b"])

def mapper(x):
    return ('first', 'second')

data['t1'], data['t2'] = data['b'].map(mapper).apply(pd.Series).values.T

print data

Giving this result:

     a    b     t1      t2
0  0.0  0.0  first  second
1  0.0  0.0  first  second
2  0.0  0.0  first  second
3  0.0  0.0  first  second
4  0.0  0.0  first  second

This might help someone else pin-down a better solution at least.

Credit to this post here too.

Edit, found a nicer way to fix it. Use:

data[['t1', 't2']] = data['b'].map(mapper).apply(pd.Series)

So, in your case, this should work:

df[['t1', 't2']] = df['zRow'].map(ReturnDateRange).apply(pd.Series)
Community
  • 1
  • 1
Stygies
  • 131
  • 5