Reputation: 351
I am using a for loop to update a Numpy Array but it doesn't seem to be working. What am I doing wrong?
My code
import pandas as pd
import pandas_datareader as pdr
import datetime as dt
from dateutil.relativedelta import relativedelta
import matplotlib.finance as mf
import numpy as np
import scipy as sp
def pull_price(ticker):
df = pd.read_csv(ticker+'.csv')
df1=np.array(df['Adj Close'])
return df1
tickers=['^DJI','^GSPC','^IXIC','^GDAXI','^HSI','^FCHI','^N225']
dic={}
for i in tickers:
dic[i]=pull_price(i)
for i in tickers:
count = len(dic[i])
for j in range(0,count):
try:
dic[i][j] = float(dic[i][j])
except ValueError:
dic[i][j] = float(dic[i][j-1])
dic_1= dic
print(dic['^GSPC'][0])
for i in tickers:
count = len(dic_1[i])
for j in range(0,count):
dic_1[i][j] = np.log(dic_1[i][j])
print(dic_1['^GSPC'][0])
print(dic['^GSPC'][0])
My output for the 3 Print commands in sequence
411.410004
6.01959029389
6.01959029389
For the 1st Print
command it shows me the correct value.
But for the next 2 Print
Commands why is it showing the same value. I am only updating dic_1
and not dic
. What am I doing wrong?
Upvotes: 0
Views: 46
Reputation: 1611
When you do:
dict1 = dict(a=1)
dict2 = dict1
Both dict1 and dict2 point to the same dictionary. The names are different, but both names refer to the same data structure. That means:
dict2['a'] = 2
print(dict1)
{'a': 2}
If you want dict2 to be a copy of dict1, explicitly make it a copy:
dict2 = dict1.copy()
Ah, and because the elements of your dictionary are themselves also dictionaries, you need to make a deep copy:
import deepcopy
dict2 = deepcopy.copy(dict1)
Upvotes: 1