Return Only The Last Day Of The Year With Pandas?
Made an api get request for the historical close prices of a stock for a specified company from the financialmodelingprep api. It returns every recorded date for the stock. The pro
Solution 1:
df2 = df.groupby(pd.DatetimeIndex(df['date']).year,
as_index=False).agg({'date': max}).reset_index(drop=True)
date symbol close01970-09-14 MMM 0.32260012020-12-04 MMM 172.460007
Here the dataframe is grouped by the year of date
column, then the rows with maximum date per year are returned. Then you can sort it by date and get the five last rows:
df2.sort_values('date').iloc[-5:]
Solution 2:
You can use pandas function called iloc. This function gives out a certain number of rows of your pd dataframe. So you could ask for information from it like a list, ex: pandas.iloc[-1]
This is an example of how it works:
mydict= [{'a':1, 'b':2, 'c':3, 'd':4},
{'a':100, 'b':200, 'c':300, 'd':400},
{'a':1000, 'b':2000, 'c':3000, 'd':4000 }]
df=pd.DataFrame(mydict)df.iloc[-1]
outputs the last row:
a1000b2000c3000d4000Name:2,dtype:int64
using pd.iloc[0] outputs the first row:
a1b2
c 3
d 4
Name: 0, dtype: int64
Now if you wanted the last date every 5 years you could loop over the array and take ranges of data. In this case 5 year ranges. So it would be something like this:
arrayofData=company_stock_price['close']
every5YearsData = []
for i in range(len(arrayofData)):
fiveYearList=[]
if arrayofData[i] % 5!=0:
fiveYearList.append(arrayofData[i])
else:
every5YearsData.append(fiveYearList[0])
Solution 3:
You can get the recent date and use .loc()
for getting the desired row like so:
recent_date = company_stock_price["date"].max()
latest_stock_price = company_stock_price.loc[company_stock_price['date'] == recent_date]
Post a Comment for "Return Only The Last Day Of The Year With Pandas?"