Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
DataFrame Assignment
#1
I get a dataframe to df1 and assign it to df2 to keep a copy.
Not sure why but when df1 is changed, df2 is also changed.
Is there a way to save and keep a copy in a variable without change? Thanks.

import googlefinance.client as gf

param = {'q': 'FB','i': "300",'x': "NASD",'p': "15m"}
df1 = gf.get_price_data(param)
print('Get dataframe in df1: ')
print(df1)
df2 = df1
df1['Symbol'] = 'FB'
print('\nAfter add column in df1: ')
print(df1)
print('\nThe column is also added in df2: ')
print(df2)
Reply
#2
Hello

If you do a df2 = df1 reference is maintained and df2 will change when you make changes to df1

Instead try

df2 = df1.copy(deep=True)
I tried with small example and it works for me

import pandas as pd
b = pd.DataFrame()
a = pd.DataFrame({'date':['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],'Holiday':['Sunday','Wednesday','Tuesday','Saturday','Saturday','Tuesday','Wednesday','Sunday','Sunday','Sunday','Sunday','Thursday']})
b = a.copy(deep=True)
a.iloc[[2],[0]] ='Wednesday'
print (a)
print (b)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020