0

Here are two sample dataframes. How can we add a new column to the DF2 and title it 'Month' and for column 1 in DF2, vlookup on Column 1 in DF1 to find Column 2 and add in month to new column in DF2.

df1 = pd.DataFrame([['1', Jan],
                   ['2', Feb],
                   ['3', March],
                   ['4', April],
                   ['5', May]], columns=['Month#', 'Month'])

df2 = pd.DataFrame([['1', 113],
                   ['2', 113],
                   ['3', 301],
                   ['4', 122],
                   ['5', 113]], columns=['num', 'num_letter'])

I this this error: KeyError Traceback (most recent call last) /usr/local/lib/python3.9/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3628 try: -> 3629 return self._engine.get_loc(casted_key) 3630 except KeyError as err:

9 frames 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: 'M01'

The above exception was the direct cause of the following exception:

KeyError Traceback (most recent call last) /usr/local/lib/python3.9/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3629 return self._engine.get_loc(casted_key) 3630 except KeyError as err: -> 3631 raise KeyError(key) from err 3632 except TypeError: 3633 # If we have a listlike key, _check_indexing_error will raise

KeyError: 'M01'

I tried this, but it fails:

df2['month'] = df1['month#'].apply(lambda x: df1[x])

I am trying to add a new column to DF2 and bring over the 'Month' so the result would be like:

['1', 113, Jan '2', 113, Feb ]

and so on.

0 Answers0