python add columns to dataframe without changing the original

Solutions on MaxInterview for python add columns to dataframe without changing the original by the best coders in the world

showing results for - "python add columns to dataframe without changing the original"
Mika
07 Jun 2017
1#given an original pandas.DataFrame named 'df', and the data series that we want to associate with the new column named 's', 3 possible solutions:
2
3#1-Use "assign()" to create new column and then assign values to it
4df_w_new_col = df.assign (name='New_Col')
5
6#2-create an aditional Dataframe with just the new column to add and concatenate with the old dataframe. Like a great majority of pandas methods, this actually creates a new df, it does not just concatenate to the old one so it is safe to change the old and new df's independetly
7df = pd.concat( [df, pd.DataFrame({'New_Col:s})], axis=1 )
8
9#3-explicitely create a copy and append a column
10df2 = df.copy()
11df2['New_Col'] = s