I am looking to create new columns in a pandas dataframe based on other column value using apply. I receive this error and I don't understand why:
File "C:\dev\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2448, in _setitem_array
raise ValueError('Columns must be same length as key')
ValueError: Columns must be same length as key
Am I misunderstanding the apply function? Can you update/create multiple columns using a single apply call?
Here is my sample data:
import pandas as pd
x = pd.DataFrame({'VP': ['Brian', 'Sarah', 'Sarah', 'Brian', 'Sarah'],
'Director': ['Jim', 'Ian', 'Ian', 'Jim', 'Jerry'],
'Requester': ['Kelly', 'Dave', 'Jordan', 'Matt', 'Rob'],
'VP from Query': ['Jordan', 'Justin', 'Sarah', 'Brian', 'Sarah'],
'Director from Query': ['Other', 'Other', 'Ian', 'Jim', 'Jerry'],
'Requester from Query': ['Kelly', 'Dave', 'Jordan', 'Matt', 'Rob']
})
x = x[['VP', 'Director', 'Requester', 'VP from Query', 'Director from Query', 'Requester from Query']]
def set_suggested_hierarchy(row):
if row['VP'] != row['VP from Query']:
return row[['VP', 'Director']]
else:
return row[['VP from Query', 'Director from Query']]
x[['Suggested VP', 'Suggested Director']] = x.apply(lambda row: set_suggested_hierarchy(row), axis=1)
Thank you so much