Insert A Column To A Pandas Dataframe
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 w
Solution 1:
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.
Solution 2:
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
Post a Comment for "Insert A Column To A Pandas Dataframe"