I want to add total fields to this DataFrame:
df_test = pd.DataFrame([
{'id':1,'cat1a':3,'cat1b':2, 'cat2a':4,'cat2b':3},
{'id':2,'cat1a':7,'cat1b':5, 'cat2a':9,'cat2b':6}
])
This code almost works:
def add_total(therecord):
t1 = therecord['cat1a'] + therecord['cat1b']
t2 = therecord['cat2a'] + therecord['cat2b']
return t1, t2
df_test['cat1tot', 'cat2tot'] = df_test[['cat1a', 'cat1b', 'cat2a', 'cat2b']].apply(add_total,axis=1)
Except it results in only 1 new column:
And this code:
def add_total(therecord):
t1 = therecord['cat1a'] + therecord['cat1b']
t2 = therecord['cat2a'] + therecord['cat2b']
return [t1, t2]
df_test[['cat1tot', 'cat2tot']] = df_test[['cat1a', 'cat1b', 'cat2a', 'cat2b']].apply(add_total,axis=1)
Results in: KeyError: "['cat1tot' 'cat2tot'] not in index"
I tried to resolve that with:
my_cols_list=['cat1tot','cat2tot']
df_test.reindex(columns=[*df_test.columns.tolist(), *my_cols_list], fill_value=0)
But that didn't solve the problem. So what am I missing?