I would like to replace entire columns of a pandas dataframe with other columns, for example:

enter image description here

and I would like to replace the columns A and B. What I did is the following:


or also


but it does not work. In particular I get the following error:

KeyError: 'opcodes'

in both cases. Can anyone help me? Thank's in advance.

[EDIT] The original dataframe is the following:

enter image description here

on which I did the following modification:

dataFrame['opcodes'] = dataFrame['instructions'].apply(lambda x:[i.split()  [0] for i in x])

now I would like to define an other dataframe on which only the 'opt' column and a column with the values 'opcodes' appear.

  • $\begingroup$ See my edit below for clarification $\endgroup$
    – HFulcher
    Nov 1, 2019 at 14:56

1 Answer 1


You are getting a KeyError because 'opcodes' doesn't exist in dataFrame. Can you show us the contents of dataFrame not just df?


You don't need to create an empty DataFrame and then apply the data across. Simply do:

df = dataFrame[["opt", "opcodes"]].copy()
  • $\begingroup$ Thank's for your answer. By doing is it gives me the following error message: KeyError: "['opcodes'] not in index" $\endgroup$
    – J.D.
    Nov 1, 2019 at 15:02
  • $\begingroup$ Something strange is happening with your dataframe where you are creating opcodes. Are you 100% sure that what you are using has the opcodes column within it? @J.D. $\endgroup$
    – HFulcher
    Nov 1, 2019 at 15:03
  • $\begingroup$ I reloaded all the cells in my jupyter notebook and now it is working fine. Thank you vey much. $\endgroup$
    – J.D.
    Nov 1, 2019 at 15:15
  • $\begingroup$ Happy to help :) $\endgroup$
    – HFulcher
    Nov 1, 2019 at 15:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.