I would like to automate the following code line:
df_b = df_b.append([{'A':df_a['A'][1], 'B':df_a['B'][1], 'C':df_a['C'][1]}], ignore_index=True)
and I was considering using a lambda function to do so:
list = ['A', 'B', 'C']
func = lambda j: df_a[j][1]
df_b = df_b.append([{(func(list))}], ignore_index=True)
And I got the following error:
KeyError Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2896 try:
-> 2897 return self._engine.get_loc(key)
2898 except KeyError:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 1
What would be your advice to run such a lambda function? Thanks
I think what you want here is a dictionary comprehension:
lst = ['A', 'B', 'C']
func = lambda j: df_a[j][1]
to_append = {s:func(s) for s in lst}
df_b = df_b.append([to_append], ignore_index=True)
As a side note, you could equally define func
with a def
instead of lambda
in this case.