Home > Enterprise >  'Columns must be same length as key' trying to populate two columns in pandas
'Columns must be same length as key' trying to populate two columns in pandas

Time:06-17

This pandas code works fine:

mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]

df = pd.DataFrame(mydict)

def exec_func(dfx):
    x, y = dfx['a']   1, dfx['b']   1 
    return x

df['e'] = df.apply(exec_func, axis=1)

print(df)

    a    b    c    d    e
0   1    2    3    4    2
1   100  200  300  400  101
2   1000 2000 3000 4000 1001

However if I want to return two values and update two columns it throws an error:

def exec_func(dfx):
    x, y = dfx['a']   1, dfx['b']   1 
    return x, y

df[['e', 'f']] = df.apply(exec_func, axis=1)

throws: ValueError: Columns must be same length as key

How to fix this? Note that I need to use apply

CodePudding user response:

If you absolutely need to use apply, you can make the return value as a series (But try to use @BENY's answer):

def exec_func(dfx):
    x, y = dfx['a']   1, dfx['b']   1 
    return pd.Series([x, y])

df[["e", "f"]] = df.apply(exec_func, axis=1)

Output:

      a     b     c     d     e     f
0     1     2     3     4     2     3
1   100   200   300   400   101   201
2  1000  2000  3000  4000  1001  2001
  • Related