Please tell me how to get only values for a specific year in Python.

Asked 2 years ago, Updated 2 years ago, 32 views

Creating two data frames to get values for a particular year is not working.

start='1976-01-01' 
end='2020-01-01'
df1 = data.DataReader('^N225', 'yahoo', start, end)

For df2,

year elementary school middle school high school
0   1976    13,312  5,743   6,420
1   1979    16,034  6,215   5,904
2   1982    20,023  9,609   7,331
3   1985    19,583  10,109  7,987
4   1988    17,368  10,417  8,791

We have data from 1976 to every three years.

I'd like to compare df1 and df2 and put df1 together in years to get the values according to the Western calendar of df2 every three years, but it doesn't work.

#df1
year=df1.index
price=df1 ['Adj Close' ]

df1 = df1.resample('Y') .max()

#df2
df['Elementary School'] = df['Elementary School'].str.replace(', ', ').astype(np.int)
df['Middle School'] = df['Middle School'].str.replace(', ', ').astype(np.int)
df['high school'] = df['high school'].str.replace(', ', ').astype(np.int)

As shown in , I will be able to add up.

nikkei_year=[]
nikkei_price=[ ]

for i in list (df2['year']):
    if i == df1 ['year]:
        nikkei_year.append(i)
        nikkei_price.append(df['price'])

I tried, but an error occurred.

for i in list (df2['year']):
---->5 if i==df ['year']:
      6nikkei_year.append(i)
      7nikkei_price.append(df['price'])

ValueError: The true value of an array with more than one element is ambivalent.Use a.any() or a.all()

I would appreciate it if you could tell me how to solve this problem!

Additional
df1.

High Low Open Close Volume Adj Close
Date                        
1976-01-05  4403.060059 4403.060059 4403.060059 4403.060059 0.0 4403.060059
1976-01-06  4449.700195 4449.700195 4449.700195 4449.700195 0.0 4449.700195
1976-01-07  4469.100098 4469.100098 4469.100098 4469.100098 0.0 4469.100098
1976-01-08  4485.770020 4485.770020 4485.770020 4485.770020 0.0 4485.770020
1976-01-09  4484.049805 4484.049805 4484.049805 4484.049805 0.0 4484.049805

python python3

2022-09-29 22:53

1 Answers

Please change the two parts as follows.

From:

#df1
year=df1.index
price=df1 ['Adj Close' ]

Modified

#df1
df1['year'] = df1.index.year
df1['price'] = df1['Adj Close']

From:

 if i==df1['year]:
        nikkei_year.append(i)
        nikkei_price.append(df['price'])

Modified

df=df1[df1['year']==i]
    if not df.empty:
        nikkei_year.append(i)
        nikkei_price.append(df['price'])


2022-09-29 22:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.