5

Scenario: I have a code that reads data from excel worksheets into dataframes, merges into one dataframe, and perform some cleaning procedures.

Issue: I am trying to add a column with a given value to the beginning of the dataframe with pd.insert, but every time I run this line the dataframe disappears from the variable explorer.

This is the line I am using:

fnl = fnl.insert(loc=1, column='N', value=15)

Question: Why could be the reason for this, and how to fix it?

2 Answers 2

11

pd.DataFrame.insert acts in place and doesn't return anything. All you need is

fnl.insert(1, 'N', 15)

Because it returns nothing, you were assigning None to fnl and that's why it was disappearing.

1
  • Spot on, thanks for the help. I will accept the answer as soon as the time lock opens.
    – DGMS89
    Commented Aug 23, 2017 at 16:22
4

You could also append it to the end of the dataframe (the order of the columns generally shouldn't matter except for presentation purposes).

fnl = fnl.assign(N=15)

This returns a copy of the dataframe with the new column N added with values equal to 15.

Because the index doesn't matter in this case, it should be more efficient to append via:

fnl['N'] = 15
2
  • with a bit of hackery df.assign(N=15).iloc[:, [-1] + list(range(df.shape[1]))]
    – piRSquared
    Commented Aug 23, 2017 at 16:42
  • 1
    Or df.assign(N=15).loc[:, ['N'] + df.columns.tolist()]
    – Alexander
    Commented Aug 23, 2017 at 16:46

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