0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is OK, but the lambda function is so trivial here that it would be clearer to directly implement its content in the dictionnary comprehension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.