remove non matching rows from two dataframes python - python

I have two dataframes
1st
dt SRNE CRSR GME ... ASO TH DTE ATH
0 2021-04-12 00:00:00 6.940 33.67 141.09 ... 32.29 3.42 135.63 50.80
1 2021-04-13 00:00:00 6.930 33.71 140.99 ... 31.68 3.39 137.63 50.88
2 2021-04-14 00:00:00 7.385 33.93 166.53 ... 30.82 3.23 138.72 53.35
3 2021-04-15 00:00:00 7.440 34.16 156.44 ... 30.54 3.26 139.48 54.14
4 2021-04-16 00:00:00 7.490 32.60 154.69 ... 30.77 2.79 140.68 55.45
2nd
dt text compare
0 2021-03-19 14:59:49+00:00 i only need uxy to hit 20 eod to make up for a... 1
1 2021-03-19 14:59:51+00:00 oh this isn’t good 0
2 2021-03-19 14:59:51+00:00 lads why is my account covered in more red ink... 0
3 2021-03-19 14:59:51+00:00 i'm tempted to drop my last 800 into some stup... 0
4 2021-03-19 14:59:52+00:00 the sell offs will continue until moral improves. 0
I want to remove rows that don't match with both dataframes by looking at the data column.
I tried
discussion = discussion[discussion['dt'] == price['dt']]
It gives an error ValueError: Can only compare identically-labeled Series objects
I assume it is because the column names don't match
Appreciate your help

import pandas as pd
discussion = pd.DataFrame([['2021-04-12 00:00:00',6.940,33.67,141.09,32.29, 3.42, 135.63, 50.80],
['2021-04-13 00:00:00',6.930,33.71,140.99,31.68, 3.39, 137.63, 50.88],
['2021-04-14 00:00:00',7.385,33.93,166.53,30.82, 3.23, 138.72, 53.35],
['2021-04-15 00:00:00',7.440,34.16,156.44,30.54, 3.26, 139.48, 54.14],
['2021-04-16 00:00:00',7.490,32.60,154.69,30.77, 2.79, 140.68, 55.45]],
columns=['dt', 'SRNE', 'CRSR', 'GME', 'ASO', 'TH', 'DTE', 'ATH'])
discussion['dt'] = pd.to_datetime(discussion['dt'])
price = pd.DataFrame([['2021-04-12 23:30:00','i only need uxy to hit 20 eod to make up for a...', 1],
['2021-03-19 14:59:51+00:00','oh this isn’t good ',0],
['2021-03-19 14:59:51+00:00','lads why is my account covered in more red ink... ', 0],
['2021-03-19 14:59:51+00:00','im tempted to drop my last 800 into some stup... ', 0],
['2021-04-16 12:45:00','the sell offs will continue until moral improves. ', 0]],
columns=['dt', 'text', 'compare'])
price['dt'] = pd.to_datetime(price['dt'], utc=True)
discussion = discussion[discussion['dt'].dt.date.isin(price['dt'].dt.date)]
discussion
Output
dt SRNE CRSR GME ASO TH DTE ATH
0 2021-04-12 6.94 33.67 141.09 32.29 3.42 135.63 50.80
4 2021-04-16 7.49 32.60 154.69 30.77 2.79 140.68 55.45

Related

How do I apply a function to transform a numeric variable based on the cumulative count of a string variable?

I am trying to transform a numerical variable based on the weekly count of a string variable using this basic function.
import numpy as np
import pandas as pd
def adstock(grps, rate):
adstock = np.zeros(len(grps))
adstock[0] = grps[0]
for i in range(1, len(grps)):
adstock[i] = grps[i] + rate * adstock[i - 1]
return adstock
I.e., for each creative, I need the transformation to only affect the subsequent weeks and not the first week.
df = pd.DataFrame(
{
"Creative": [
"Phone",
"Phone",
"Phone",
"Yoga",
"Yoga",
"Yoga",
"Yoga",
"Grass",
"Grass",
"Grass",
"Grass",
],
"airing_week": [
"2015-12-28",
"2016-01-04",
"2016-01-11",
"2018-01-01",
"2018-01-08",
"2018-01-15",
"2018-01-22",
"2022-02-28",
"2022-03-07",
"2022-03-14",
"2022-03-21",
],
"week_num": [1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4],
"grps": [
38.5,
67.13,
50.15,
43.11,
28.61,
9.04,
4.02,
28.83,
28.81,
36.91,
37.79,
],
}
)
df['adstock_grps']=adstock(df['grps'], .5)
df
Output:
Creative airing_week week grps adstock_grps
0 Phone 2015-12-28 1 38.50 38.500000
1 Phone 2016-01-04 2 67.13 86.380000
2 Phone 2016-01-11 3 50.15 93.340000
3 Yoga 2018-01-01 1 43.11 89.780000
4 Yoga 2018-01-08 2 28.61 73.500000
5 Yoga 2018-01-15 3 9.04 45.790000
6 Yoga 2018-01-22 4 4.02 26.915000
7 Grass 2022-02-28 1 28.83 42.287500
8 Grass 2022-03-07 2 28.81 49.953750
9 Grass 2022-03-14 3 36.91 61.886875
10 Grass 2022-03-21 4 37.79 68.733437
But, as you see, the transformation is incorrect as it is linear and based on the index. I need the transformation to occur for each creative after the first week and not carry over to the other creatives.
Many thanks!
With the dataframe you provided, here is one way to do it by chunking it per Creative values, apply adstock, and concatenate chunks back:
df = pd.concat(
[
df.loc[df["Creative"] == creative, :]
.reset_index(drop=True)
.pipe(lambda df_: df_.assign(adstock_grps=adstock(df_["grps"], 0.5)))
for creative in df["Creative"].unique()
]
).reset_index(drop=True)
print(df)
# Output
Creative airing_week week_num grps adstock_grps
0 Phone 2015-12-28 1 38.50 38.50000
1 Phone 2016-01-04 2 67.13 86.38000
2 Phone 2016-01-11 3 50.15 93.34000
3 Yoga 2018-01-01 1 43.11 43.11000
4 Yoga 2018-01-08 2 28.61 50.16500
5 Yoga 2018-01-15 3 9.04 34.12250
6 Yoga 2018-01-22 4 4.02 21.08125
7 Grass 2022-02-28 1 28.83 28.83000
8 Grass 2022-03-07 2 28.81 43.22500
9 Grass 2022-03-14 3 36.91 58.52250
10 Grass 2022-03-21 4 37.79 67.05125

merge pandas dataframe causing duplicate row values

I have two pandas dataframe that I want to merge. My first dataframe, names, is a list of stock tickers and corresponding dates. Example below:
Date Symbol DateSym
0 2017-01-05 AGRX AGRX01-05-2017
1 2017-01-05 TMDI TMDI01-05-2017
2 2017-01-06 ATHE ATHE01-06-2017
3 2017-01-06 AVTX AVTX01-06-2017
4 2017-01-09 CVM CVM01-09-2017
5 2017-01-10 DFFN DFFN01-10-2017
6 2017-01-10 VKTX VKTX01-10-2017
7 2017-01-11 BIOC BIOC01-11-2017
8 2017-01-11 CVM CVM01-11-2017
9 2017-01-11 PALI PALI01-11-2017
I created another dataframe, price1, that loops through the tickers and creates a dataframe with the open, high, low, close and other relevant info I need. When I merge the two dataframes together, I want to only show the names dataframe on the left with the corresponding price data on the right. What I ran a test of the first 10 tickers, I noticed that the combined dataframe is outputting redundant rows. (See CVM in row 4 and 5 below), even though the price1 dataframe doesn't have duplicate values. What am I doing wrong?
def price_stats(df):
# df['ticker'] = df
df['Gap Up%'] = df['Open'] / df['Close'].shift(1) - 1
df['HOD%'] = df['High'] / df['Open'] - 1
df['Close vs Open%'] = df['Close'] / df['Open'] - 1
df['Close%'] = df['Close'] / df['Close'].shift(1) - 1
df['GU and Goes Red'] = np.where((df['Low'] < df['Close'].shift(1)) & (df['Open'] > df['Close'].shift(1)), 1, 0)
df['Yday Intraday>30%'] = np.where((df['Close vs Open%'].shift(1) > .30), 1, 0)
df['Gap Up?'] = np.where((df['Gap Up%'] > 0), 1, 0)
df['Sloppy $ Vol'] = (df['High'] + df['Low'] + df['Close']) / 3 * df['Volume']
df['Prev Day Sloppy $ Vol'] = (df['High'].shift(1) + df['Low'].shift(1) + df['Close'].shift(1)) / 3 * df[
'Volume'].shift(1)
df['Prev Open'] = df['Open'].shift(1)
df['Prev High'] = df['High'].shift(1)
df['Prev Low'] = df['Low'].shift(1)
df['Prev Close'] = df['Close'].shift(1)
df['Prev Vol'] = df['Volume'].shift(1)
df['D-2 Close'] = df['Close'].shift(2)
df['D-2 Vol'] = df['Volume'].shift(2)
df['D-3 Close']= df['Close'].shift(3)
df['D-2 Open'] = df['Open'].shift(2)
df['D-2 High'] = df['High'].shift(2)
df['D-2 Low'] = df['Low'].shift(2)
df['D-2 Intraday Rnage'] = df['D-2 Close']/df['D-2 Open']-1
df['D-2 Close%'] = df['D-2 Close']/df['D-3 Close']-1
df.dropna(inplace=True)
vol_excel = pd.read_excel('C://U******.xlsx')
names = vol_excel.Symbol.to_list()
price1 = []
price1 = pd.DataFrame(price1)
for name in names[0:10]:
print(name)
price = yf.download(name, start="2016-12-01", end="2022-03-04")
price['ticker'] = name
price_stats(price)
price1 = pd.concat([price1, price])
price1 = price1.reset_index()
orig_day = pd.to_datetime(price1['Date'])
price1['Prev Day Date'] = orig_day - pd.tseries.offsets.CustomBusinessDay(1, holidays=nyse.holidays().holidays)
price1['DateSym'] = price1['ticker']+ price1['Date'].dt.strftime('%m-%d-%Y')
price1 = price1.rename(columns={'ticker':'Symbol'})
datesym = price1['DateSym']
price1.drop(labels=['DateSym'], axis=1,inplace = True)
price1.insert(0, 'DateSym', datesym)
vol_excel['DateSym'] = vol_excel['Symbol']+vol_excel['Date'].dt.strftime('%m-%d-%Y')
dfcombo = vol_excel.merge(price1,on=['Date','Symbol'],how='inner')
See how CVM is duplicated twice when i print out dfcombo
Date Symbol DateSym_x DateSym_y Open High Low Close Adj Close Volume ... Prev Vol D-2 Close D-2 Vol D-3 Close D-2 Open D-2 High D-2 Low D-2 Intraday Rnage D-2 Close% Prev Day Date
0 2017-01-05 AGRX AGRX01-05-2017 AGRX01-05-2017 2.71 2.71 2.40 2.52 2.52 2408400 ... 18584900.0 5.000 2390400.0 5.700000 5.770 5.813000 4.460 -0.133449 -0.122807 2017-01-04
1 2017-01-05 TMDI TMDI01-05-2017 TMDI01-05-2017 15.60 16.50 12.90 13.50 13.50 43830 ... 114327.0 10.500 61543.0 7.200000 7.500 10.500000 7.500 0.400000 0.458333 2017-01-04
2 2017-01-06 ATHE ATHE01-06-2017 ATHE01-06-2017 2.58 2.60 2.23 2.42 2.42 222500 ... 1750700.0 1.930 53900.0 1.750000 1.790 1.950000 1.790 0.078212 0.102857 2017-01-05
3 2017-01-06 AVTX AVTX01-06-2017 AVTX01-06-2017 1.24 1.24 1.02 1.07 1.07 480500 ... 1246100.0 0.883 44900.0 0.890000 0.896 0.950000 0.827 -0.014509 -0.007865 2017-01-05
4 2017-01-09 CVM CVM01-09-2017 CVM01-09-2017 2.75 3.00 2.75 2.75 2.75 376520 ... 414056.0 2.000 77360.0 2.000000 2.000 2.250000 2.000 0.000000 0.000000 2017-01-06
5 2017-01-09 CVM CVM01-09-2017 CVM01-09-2017 2.75 3.00 2.75 2.75 2.75 376520 ... 414056.0 2.000 77360.0 2.000000 2.000 2.250000 2.000 0.000000 0.000000 2017-01-06
6 2017-01-10 DFFN DFFN01-10-2017 DFFN01-10-2017 111.00 232.50 108.75 125.25 125.25 165407 ... 43167.0 30.900 67.0 34.650002 31.500 34.349998 30.900 -0.019048 -0.108225 2017-01-09
7 2017-01-10 VKTX VKTX01-10-2017 VKTX01-10-2017 1.64 1.64 1.43 1.56 1.56 981700 ... 1550400.0 1.260 264900.0 1.230000 1.250 1.299000 1.210 0.008000 0.024390 2017-01-09
8 2017-01-11 BIOC BIOC01-11-2017 BIOC01-11-2017 858.00 1017.00 630.00 813.00 813.00 210182 ... 78392.0 306.000 5368.0 285.000000 285.000 315.000000 285.000 0.073684 0.073684 2017-01-10
9 2017-01-11 CVM CVM01-11-2017 CVM01-11-2017 4.25 4.50 3.00 3.75 3.75 487584 ... 672692.0 2.750 376520.0 2.750000 2.750 3.000000 2.750 0.000000 0.000000 2017-01-10
I'm wondering since the names dataframe may have the same tickers, but different dates, in the dataframe and each time the price1 dataframe is pulling the price data and adding to that price1 dataframe maybe causing the issue.
For example, in the names dataframe, AGRX can be listed for the date 2017-01-05 and 2020-12-20. My loop function as shown pulls from yahoo data and appends it to the price1 dataframe even though its the same set of data. Along the same token, is there a way for me to skip appending that duplicate ticker and will that solve the issue?

Python Pandas Dataframe idxmax is so slow. Alternatives?

I'm trying to select rows out of groups by max value using df.loc[df.groupby(keys)['column'].idxmax()].
I'm finding, however, that df.groupby(keys)['column'].idxmax() takes a really long time on my dataset of about 27M rows. Interestingly, running df.groupby(keys)['column'].max() on my dataset takes only 13 seconds while running df.groupby(keys)['column'].idxmax() takes 55 minutes. I don't understand why returning the indexes of the rows takes 250 times longer than returning a value from the row. Maybe there is something I can do to speed up idxmax?
If not, is there an alternative way of selecting rows out of groups by max value that might be faster than using idxmax?
For additional info, I'm using two keys and sorted the dataframe on those keys prior to the groupby and idxmax operations. Here's what it looks like in Jupyter Notebook:
import pandas as pd
df = pd.read_csv('/data/Broadband Data/fbd_us_without_satellite_jun2019_v1.csv', encoding='ANSI', \
usecols=['BlockCode', 'HocoNum', 'HocoFinal', 'TechCode', 'Consumer', 'MaxAdDown', 'MaxAdUp'])
%%time
df = df[df.Consumer == 1]
df.sort_values(['BlockCode', 'HocoNum'], inplace=True)
print(df)
HocoNum HocoFinal BlockCode TechCode
4631064 130077 AT&T Inc. 10010201001000 10
4679561 130077 AT&T Inc. 10010201001000 11
28163032 130235 Charter Communications 10010201001000 43
11134756 131480 WideOpenWest Finance, LLC 10010201001000 42
11174634 131480 WideOpenWest Finance, LLC 10010201001000 50
... ... ... ... ...
15389917 190062 Broadband VI, LLC 780309900000014 70
10930322 130081 ATN International, Inc. 780309900000015 70
15389918 190062 Broadband VI, LLC 780309900000015 70
10930323 130081 ATN International, Inc. 780309900000016 70
15389919 190062 Broadband VI, LLC 780309900000016 70
Consumer MaxAdDown MaxAdUp
4631064 1 6.0 0.512
4679561 1 18.0 0.768
28163032 1 940.0 35.000
11134756 1 1000.0 50.000
11174634 1 1000.0 50.000
... ... ... ...
15389917 1 25.0 5.000
10930322 1 25.0 5.000
15389918 1 25.0 5.000
10930323 1 25.0 5.000
15389919 1 25.0 5.000
[26991941 rows x 7 columns]
Wall time: 21.6 s
%time df.groupby(['BlockCode', 'HocoNum'])['MaxAdDown'].max()
Wall time: 13 s
BlockCode HocoNum
10010201001000 130077 18.0
130235 940.0
131480 1000.0
10010201001001 130235 940.0
10010201001002 130077 6.0
...
780309900000014 190062 25.0
780309900000015 130081 25.0
190062 25.0
780309900000016 130081 25.0
190062 25.0
Name: MaxAdDown, Length: 20613795, dtype: float64
%time df.groupby(['BlockCode', 'HocoNum'])['MaxAdDown'].idxmax()
Wall time: 55min 24s
BlockCode HocoNum
10010201001000 130077 4679561
130235 28163032
131480 11134756
10010201001001 130235 28163033
10010201001002 130077 4637222
...
780309900000014 190062 15389917
780309900000015 130081 10930322
190062 15389918
780309900000016 130081 10930323
190062 15389919
Name: MaxAdDown, Length: 20613795, dtype: int64
You'll see in the very first rows of data there are two entries for AT&T in the same BlockCode, one for MaxAdDown of 6Mbps and one for 18Mbps. I want to keep the 18Mbps row and drop the 6Mbps row, so that there is one row per company per BlockCode that has the the maximum MaxAdDown value. I need the entire row, not just the MaxAdDown value.
sort and drop duplicates:
df.sort('MaxAdDown').drop_duplicates(['BlockCode', 'HocoNum'], keep='last')

Data cleaning and preparation for Time-Series-LSTM

I need to prepare my Data to feed it into an LSTM for predicting the next day.
My Dataset is a time series in seconds but I have just 3-5 hours a day of Data. (I just have this specific Dataset so can't change it)
I have Date-Time and a certain Value.
E.g.:
datetime..............Value
2015-03-15 12:00:00...1000
2015-03-15 12:00:01....10
.
.
I would like to write a code where I extract e.g. 4 hours and delete the first extracted hour just for specific months (because this data is faulty).
I managed to write a code to extract e.g. 2 hours for x-Data (Input) and y-Data (Output).
I hope I could explain my problem to you.
The Dataset is 1 Year in seconds Data, 6pm-11pm rest is missing.
In e.g. August-November the first hour is faulty data and needs to be deleted.
init = True
for day in np.unique(x_df.index.date):
temp = x_df.loc[(day + pd.DateOffset(hours=18)):(day + pd.DateOffset(hours=20))]
if len(temp) == 7201:
if init:
x_df1 = np.array([temp.values])
init = False
else:
#print (temp.values.shape)
x_df1 = np.append(x_df1, np.array([temp.values]), axis=0)
#else:
#if not temp.empty:
#print (temp.index[0].date(), len(temp))
x_df1 = np.array(x_df1)
print('X-Shape:', x_df1.shape,
'Y-Shape:', y_df1.shape)
#sample, timesteps and features for LSTM
X-Shape: (32, 7201, 6) Y-Shape: (32, 7201)
My expected result is to have a dataset of e.g. 4 hours a day where the first hour in e.g. August, September, and October is deleted.
I would be also very happy if there is someone who can also provide me with a nicer code to do so.
Probably not the most efficient solution, but maybe it still fits.
First lets generate some random data for the first 4 months and 5 days per month:
import random
import pandas as pd
df = pd.DataFrame()
for month in range(1,5): #First 4 Months
for day in range(5,10): #5 Days
hour = random.randint(18,19)
minute = random.randint(1,59)
dt = datetime.datetime(2018,month,day,hour,minute,0)
dti = pd.date_range(dt, periods=60*60*4, freq='S')
values = [random.randrange(1, 101, 1) for _ in range(len(dti))]
df = df.append(pd.DataFrame(values, index=dti, columns=['Value']))
Now let's define a function to filter the first row per day:
def first_value_per_day(df):
res_df = df.groupby(df.index.date).apply(lambda x: x.iloc[[0]])
res_df.index = res_df.index.droplevel(0)
return res_df
and print the results:
print(first_value_per_day(df))
Value
2018-01-05 18:31:00 85
2018-01-06 18:25:00 40
2018-01-07 19:54:00 52
2018-01-08 18:23:00 46
2018-01-09 18:08:00 51
2018-02-05 18:58:00 6
2018-02-06 19:12:00 16
2018-02-07 18:18:00 10
2018-02-08 18:32:00 50
2018-02-09 18:38:00 69
2018-03-05 19:54:00 100
2018-03-06 18:37:00 70
2018-03-07 18:58:00 26
2018-03-08 18:28:00 30
2018-03-09 18:34:00 71
2018-04-05 18:54:00 2
2018-04-06 19:16:00 100
2018-04-07 18:52:00 85
2018-04-08 19:08:00 66
2018-04-09 18:11:00 22
So, now we need a list of the specific months, that should be processed, in this case 2 and 3. Now we use the defined function and filter the days for every selected month and loop over those to find the indexes of all values inside the first entry per day +1 hour later and drop them:
MONTHS_TO_MODIFY = [2,3]
HOURS_TO_DROP = 1
fvpd = first_value_per_day(df)
for m in MONTHS_TO_MODIFY:
fvpdm = fvpd[fvpd.index.month == m]
for idx, value in fvpdm.iterrows():
start_dt = idx
end_dt = idx + datetime.timedelta(hours=HOURS_TO_DROP)
index_list = df[(df.index >= start_dt) & (df.index < end_dt)].index.tolist()
df.drop(index_list, inplace=True)
result:
print(first_value_per_day(df))
Value
2018-01-05 18:31:00 85
2018-01-06 18:25:00 40
2018-01-07 19:54:00 52
2018-01-08 18:23:00 46
2018-01-09 18:08:00 51
2018-02-05 19:58:00 1
2018-02-06 20:12:00 42
2018-02-07 19:18:00 34
2018-02-08 19:32:00 34
2018-02-09 19:38:00 61
2018-03-05 20:54:00 15
2018-03-06 19:37:00 88
2018-03-07 19:58:00 36
2018-03-08 19:28:00 38
2018-03-09 19:34:00 42
2018-04-05 18:54:00 2
2018-04-06 19:16:00 100
2018-04-07 18:52:00 85
2018-04-08 19:08:00 66
2018-04-09 18:11:00 22

Align years of daily data

Starting from a multi-annual record of temperature measured at different time in the day, I would like to end up with a rectangular array of daily averages, each row representing one year of data.
The data looks like this
temperature.head()
date
1996-01-01 00:00:00 7.39
1996-01-01 03:00:00 6.60
1996-01-01 06:00:00 7.39
1996-01-01 09:00:00 9.50
1996-01-01 12:00:00 11.00
Name: temperature, dtype: float64
I computed daily averages with
import pandas as pd
daily = temperature.groupby(pd.TimeGrouper(freq='D')).mean()
Which yields
daily.head()
date
1996-01-01 9.89625
1996-01-02 10.73625
1996-01-03 6.98500
1996-01-04 5.62250
1996-01-05 8.84625
Freq: D, Name: temperature, dtype: float64
Now for the final part I thought of something like
yearly_daily_mean = daily.groupby(pd.TimeGrouper(freq='12M', closed="left"))
but there are some issues here.
I need to drop the tail of the data not filling a complete year.
What happens if there is missing data?
How to deal with the leap years?
What is the next step? Namely, how to “stack” (in numpy's, not pandas' sense) the years of data?
I am using
array_temperature = np.column_stack([group[1] for group in yearly_daily_mean if len(group[1]) == 365])
but there should be a better way.
As a subsidiary question, how can I choose the starting day of the years of data?
If I understand you correctly, you want to reshape your timeseries of daily means (which you already calculated) to a rectangular dataframe with the different days as columns and the different years as rows.
This can be achieved easily with the pandas reshaping functions, eg with pivot:
Some dummy data:
In [45]: index = pd.date_range(start=date(1996, 1,1), end=date(2010, 6, 30), freq='D')
In [46]: daily = pd.DataFrame(index=index, data=np.random.random(size=len(index)), columns=['temperature'])
First, I add columns with the year and day of the year:
In [47]: daily['year'] = daily.index.year
In [48]: daily['day'] = daily.index.dayofyear
In [49]: daily.head()
Out[49]:
temperature year day
1996-01-01 0.081774 1996 1
1996-01-02 0.694968 1996 2
1996-01-03 0.478050 1996 3
1996-01-04 0.123844 1996 4
1996-01-05 0.426150 1996 5
Now, we can reshape this dataframe:
In [50]: daily.pivot(index='year', columns='day', values='temperature')
Out[50]:
day 1 2 ... 365 366
year ...
1996 0.081774 0.694968 ... 0.679461 0.700833
1997 0.043134 0.981707 ... 0.009357 NaN
1998 0.257077 0.297290 ... 0.701941 NaN
... ... ... ... ... ...
2008 0.047145 0.750354 ... 0.996396 0.761159
2009 0.348667 0.827057 ... 0.881424 NaN
2010 0.269743 0.872655 ... NaN NaN
[15 rows x 366 columns]
Here is how I would do it. Very simply: create a new df with the exact shape you want, then fill it with the means of the things you want.
from datetime import datetime
import numpy as np
import pandas as pd
# This is my re-creation of the data you have. (I'm calling it df1.)
# It's essential that your date-time be in datetime.datetime format, not strings
byear = 1996 # arbitrary
eyear = 2005 # arbitrary
obs_n = 50000 # arbitrary
start_time = datetime.timestamp(datetime(byear,1,1,0,0,0,0))
end_time = datetime.timestamp(datetime(eyear,12,31,23,59,59,999999))
obs_times = np.linspace(start_time,end_time,num=obs_n)
index1 = pd.Index([datetime.fromtimestamp(i) for i in obs_times])
df1 = pd.DataFrame(data=np.random.rand(obs_n)*20,index=index1,columns=['temp'])
# ^some random data
# Here is the new empty dataframe (df2) where you will put your daily averages.
index2 = pd.Index(range(byear,eyear+1))
columns2 = range(1,367) # change to 366 if you want to assume 365-day years
df2 = pd.DataFrame(index=index2,columns=columns2)
# Some quick manipulations that allow the two dfs' indexes to talk to one another.
df1['year'] = df1.index.year # a new column with the observation's year as an integer
df1['day'] = df1.index.dayofyear # a new column with the day of the year as integer
df1 = df1.reset_index().set_index(['year','day'])
# Now get the averages for each day and assign them to df2.
for year in index2:
for day in columns2[:365]: # for all but the last entry in the range
df2.loc[year,day] = df1.loc[(year,day),'temp'].mean()
if (year,366) in df1.index: # then if it's a leap year...
df2.loc[year,366] = df1.loc[(year,366),'temp'].mean()
If you don't want the final df to have any null values on that 366th day, then you can just remove the final if-statement, and rewrite columns2 = range(1,366), and then df2 will have all non-null values (assuming there was at least one measurement on every day in the observed time period).
Assuming you already have daily averages (with pd.DateTimeIndex) from your higher-frequency data as a result of:
daily = temperature.groupby(pd.TimeGrouper(freq='D')).mean()
IIUC, you want to transform the daily average into a DataFrame with an equal number of columns per row to capture annual data. You mention leap years as a potential issue when aiming for an equal number of columns.
I can imagine two ways of going about this:
Select a number of days per row - probably 365. Select rolling blocks of 365 consecutive daily data points for each row and align by index for each of these blocks.
Select years of data, filling in the gaps for leap years, and align by either MM-DD or number of day in year.
Starting with 20 1/2 years of daily random data as mock daily average temperatures:
index = pd.date_range(start=date(1995, 1,1), end=date(2015, 6, 30), freq='D')
df = pd.DataFrame(index=index, data=np.random.random(size=len(index)) * 30, columns=['temperature'])
df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 7486 entries, 1995-01-01 to 2015-06-30
Freq: D
Data columns (total 1 columns):
temperature 7486 non-null float64
dtypes: float64(1)
memory usage: 117.0 KB
None
df.head()
temperature
1995-01-01 4.119212
1995-01-02 27.107131
1995-01-03 26.704931
1995-01-04 7.430203
1995-01-05 4.230398
df.tail()
temperature
2015-06-26 10.902779
2015-06-27 8.494378
2015-06-28 17.800131
2015-06-29 19.543815
2015-06-30 16.390435
Here's a solution to the first approach:
Select blocks of 365 consecutive days using .groupby(pd.TimeGrouper('365D')), and return each resulting groupby object of daily averages as a pd.DataFrame with an integer index that runs from 0 to 364 for each sequence:
aligned = df.groupby(pd.TimeGrouper(freq='365D')).apply(lambda x: pd.DataFrame(x.squeeze().tolist())) # .squeeze() converts single columns `DataFrame` to pd.Series
To align the 21 blocks of data, just transpose the pd.DataFrame , and they will align by integer index in the columns, with the start date of each sequence in theindex. This operation will produce an extraindex, and the lastrow` will have some missing data. Clean up both with:
aligned.dropna().reset_index(-1, drop=True)
to get a [20 x 365] DataFrame as follows:
DatetimeIndex: 20 entries, 1995-01-01 to 2013-12-27
Freq: 365D
Columns: 365 entries, 0 to 364
dtypes: float64(365)
memory usage: 57.2 KB
0 1 2 3 4 5 \
1995-01-01 29.456090 25.313968 4.146206 5.347690 25.767425 11.978152
1996-01-01 25.585481 26.846486 8.336905 16.749842 6.247542 17.723733
1996-12-31 23.410462 10.168599 5.601917 11.996500 8.650726 23.362815
1997-12-31 7.586873 23.882106 22.145595 3.287160 21.642547 1.949321
1998-12-31 14.691420 3.611475 28.287327 25.347787 13.291708 20.571616
1999-12-31 25.713866 17.588570 18.562117 19.420944 12.406293 11.870750
2000-12-30 5.099561 17.894763 21.168223 4.786461 24.521417 21.443607
2001-12-30 11.791223 8.352493 12.731769 0.459697 20.680396 27.554783
2002-12-30 3.785876 0.359850 20.828764 15.376991 14.086626 0.477615
2003-12-30 23.633243 12.726250 8.197824 16.355956 8.094145 1.410746
2004-12-29 1.139949 4.161267 9.043062 14.109888 13.538735 1.566002
2005-12-29 25.504224 19.346419 3.300641 26.933084 23.634321 18.323450
2006-12-29 10.535785 9.168498 27.222106 11.962343 10.004678 23.893257
2007-12-29 27.482856 6.910670 6.033291 12.673530 26.362971 4.492178
2008-12-28 11.152316 25.233664 22.124299 11.012285 1.992814 25.542204
2009-12-28 23.131021 16.363467 1.242393 10.387653 4.858851 26.553950
2010-12-28 13.134843 9.195658 19.075850 28.539387 3.075934 8.089347
2011-12-28 28.860275 10.121573 0.663906 19.687892 29.376377 11.488446
2012-12-27 7.644073 19.649330 25.497595 6.592940 8.879444 17.733670
2013-12-27 11.713996 2.602284 3.835302 22.244623 27.279810 14.144943
6 7 8 9 ... 355 \
1995-01-01 8.210005 8.129146 28.798472 25.646924 ... 24.177163
1996-01-01 0.481487 16.772357 3.934185 22.640157 ... 23.340931
1996-12-31 10.813812 16.276504 3.422665 14.916229 ... 13.817015
1997-12-31 19.184753 28.628326 22.134871 12.721064 ... 23.905483
1998-12-31 2.839492 7.889141 17.951959 25.233585 ... 28.002751
1999-12-31 6.958672 26.335427 23.361470 5.911806 ... 7.778412
2000-12-30 8.405042 25.229016 19.746462 15.332004 ... 5.703830
2001-12-30 0.558788 15.457327 20.987186 25.452723 ... 29.771372
2002-12-30 19.002685 26.455754 25.468178 25.383786 ... 14.238987
2003-12-30 22.984328 15.934398 25.361599 12.221306 ... 1.189949
2004-12-29 22.121901 21.421103 26.175702 16.040881 ... 19.945408
2005-12-29 2.557901 15.193412 27.049389 4.825570 ... 7.629859
2006-12-29 8.582602 26.037375 0.933591 13.469771 ... 29.453932
2007-12-29 29.437921 26.470153 9.917871 16.875801 ... 5.702116
2008-12-28 3.809633 10.583385 18.029571 0.440077 ... 11.337894
2009-12-28 24.406696 28.294553 19.929563 4.683991 ... 25.697446
2010-12-28 29.765551 16.716723 6.467946 10.998447 ... 26.988863
2011-12-28 28.962746 11.407137 9.957111 4.502521 ... 14.606937
2012-12-27 1.374502 5.571244 11.212960 9.949830 ... 23.345868
2013-12-27 26.373866 4.781510 16.828510 10.280078 ... 0.552726
356 357 358 359 360 361 \
1995-01-01 13.511951 10.126835 28.121730 23.275360 11.785242 27.907039
1996-01-01 13.362737 14.336780 24.114908 28.479688 8.509069 17.408937
1996-12-31 19.192674 1.146844 27.499688 7.090407 2.777819 22.826814
1997-12-31 21.502186 10.495148 21.786895 12.229181 8.068271 6.522108
1998-12-31 21.338355 11.978265 9.186161 21.053924 3.033370 29.934703
1999-12-31 5.960120 20.325684 0.915052 15.059979 12.194240 20.138567
2000-12-30 11.883186 2.764768 27.324304 29.630706 21.852058 20.416199
2001-12-30 7.802891 25.384479 9.044486 8.809446 7.606603 6.051890
2002-12-30 7.362494 8.940783 5.259984 7.035818 24.094134 7.197113
2003-12-30 25.596902 9.756372 6.345198 1.520188 22.752717 3.470268
2004-12-29 26.789064 9.708466 18.287838 21.134643 29.862135 19.926086
2005-12-29 26.398394 24.717514 16.606042 28.189245 24.574806 14.297410
2006-12-29 8.795342 18.019536 16.579878 20.368811 22.052442 26.393676
2007-12-29 8.696240 25.901889 16.410934 15.274897 14.365867 10.523388
2008-12-28 18.581513 25.974784 21.025297 10.521118 5.864974 2.373023
2009-12-28 14.437944 21.717456 4.017870 14.024522 0.959989 17.215403
2010-12-28 11.426540 13.751451 4.664761 15.373878 7.731613 7.269089
2011-12-28 1.952897 9.406866 28.957258 20.239517 11.156958 29.238761
2012-12-27 7.588643 21.186675 17.348911 1.354323 13.918083 3.034123
2013-12-27 22.916065 2.089675 22.832061 14.787841 25.697875 14.087893
362 363 364
1995-01-01 13.107523 10.740551 20.511825
1996-01-01 25.016219 17.885332 2.438875
1996-12-31 24.692327 0.221760 6.749919
1997-12-31 24.856169 0.930019 22.603652
1998-12-31 18.361414 13.587695 25.161495
1999-12-31 0.512120 26.482288 1.035197
2000-12-30 15.401012 28.334219 5.965014
2001-12-30 10.292213 10.951915 8.270319
2002-12-30 21.945734 27.076438 6.795688
2003-12-30 14.788929 19.456459 11.216835
2004-12-29 7.086443 25.463503 17.549196
2005-12-29 12.252487 29.081547 25.507369
2006-12-29 0.012617 0.086186 17.421958
2007-12-29 4.191633 21.588891 7.516187
2008-12-28 26.194288 20.500256 24.876032
2009-12-28 28.445254 27.338754 7.849899
2010-12-28 28.888573 26.801262 23.117027
2011-12-28 19.871547 20.324514 18.369134
2012-12-27 15.907752 9.417700 4.922940
2013-12-27 21.132385 20.707216 5.288128
[20 rows x 365 columns]
If you want to simply gather the years of data and align by date, so that the non-leap years have a missing day around no 60 (as opposed to 366), you can:
df.groupby(pd.TimeGrouper(freq='A')).apply(lambda x: pd.DataFrame(x.squeeze().tolist()).T).reset_index(-1, drop=True).iloc
0 1 2 3 4 5 \
1995-12-31 1.245796 28.487530 0.574299 10.033485 19.221512 8.718728
1996-12-31 12.258653 3.864652 25.237088 13.982809 24.494746 13.822292
1997-12-31 22.239412 4.796824 21.389404 11.151171 25.577368 1.754948
1998-12-31 24.968287 2.089894 25.888487 28.291714 19.115844 24.426285
1999-12-31 9.285363 19.339405 26.012193 3.243394 25.176499 8.766770
2000-12-31 26.996573 26.404391 1.793644 21.314488 13.118279 26.703532
2001-12-31 16.303829 14.021771 20.828238 11.427195 3.099290 18.730795
2002-12-31 14.614617 10.694258 5.226033 24.900849 17.395822 22.154202
2003-12-31 10.564132 8.267639 7.778573 26.704936 5.671499 0.470963
2004-12-31 22.649623 15.725867 18.445629 7.529507 11.868134 10.965534
2005-12-31 2.406615 9.709624 23.284616 11.479254 23.814725 1.656826
2006-12-31 19.164459 23.177769 16.091672 28.936777 28.636072 4.838555
2007-12-31 12.371377 3.417582 21.067689 25.493921 25.410295 15.526614
2008-12-31 29.080385 4.653984 16.567333 24.248921 27.338538 9.353291
2009-12-31 29.608734 6.046593 22.738628 22.631714 26.061903 21.217846
2010-12-31 27.458254 15.146497 18.917073 8.473955 26.782767 10.891648
2011-12-31 25.433759 8.959650 14.343507 16.249726 17.031174 12.944418
2012-12-31 22.940797 4.791280 11.765939 25.925645 3.649440 27.483407
2013-12-31 11.684391 27.701678 27.423083 27.656086 9.374896 14.250936
2014-12-31 23.660098 27.768960 25.753294 3.014606 23.330226 17.570492
6 7 8 9 ... 356 \
1995-12-31 17.079137 26.100763 12.376462 12.315219 ... 16.910185
1996-12-31 26.718277 10.349412 12.940624 9.453769 ... 19.235435
1997-12-31 20.201528 22.895552 1.443243 20.584140 ... 29.665815
1998-12-31 21.493163 16.724328 5.946833 15.230762 ... 2.617883
1999-12-31 9.776013 13.381424 11.028295 1.905501 ... 7.200409
2000-12-31 9.773097 14.565345 22.578398 0.688273 ... 18.119020
2001-12-31 1.095308 14.817514 25.652418 8.327481 ... 15.385689
2002-12-31 29.744794 15.545211 6.373948 13.451261 ... 7.446414
2003-12-31 14.971959 25.948332 21.596976 5.355589 ... 23.676867
2004-12-31 0.604113 2.858745 0.120340 19.365223 ... 0.336213
2005-12-31 6.260722 9.819337 19.573953 11.132919 ... 26.107100
2006-12-31 10.341241 15.126506 3.349634 23.619127 ... 15.508680
2007-12-31 20.033540 22.103483 7.674852 1.263726 ... 15.148461
2008-12-31 28.233973 27.982105 17.037928 5.389418 ... 8.773618
2009-12-31 4.400039 7.284556 11.825382 4.201001 ... 6.734423
2010-12-31 26.086305 26.275027 8.069376 19.200344 ... 19.056528
2011-12-31 29.215028 0.985623 4.813478 7.752540 ... 14.395423
2012-12-31 4.690336 9.618306 25.492041 10.400292 ... 8.853903
2013-12-31 8.227096 11.013431 0.996911 15.276574 ... 26.227540
2014-12-31 23.440591 16.544698 2.263684 3.919315 ... 24.987387
357 358 359 360 361 362 \
1995-12-31 24.791125 21.443534 21.092439 8.289222 9.745293 20.084046
1996-12-31 2.632656 2.102163 24.828437 18.104255 7.951859 3.266873
1997-12-31 11.246534 14.086539 29.635519 19.518642 24.086108 6.041870
1998-12-31 29.961162 9.924863 9.401790 25.597344 13.885467 16.537406
1999-12-31 3.057125 15.241720 8.472388 3.248545 11.302522 19.283612
2000-12-31 22.999729 17.518504 10.058249 2.953903 10.167712 17.309525
2001-12-31 18.267445 23.205300 25.658591 19.915797 10.704525 26.604965
2002-12-31 11.497110 3.641206 9.693428 24.571510 6.438652 29.280098
2003-12-31 23.931401 19.967615 0.307896 0.385782 0.579257 7.534806
2004-12-31 21.321146 9.224362 1.703842 6.180944 28.173925 5.178336
2005-12-31 17.990409 28.746179 2.524899 10.555224 25.487723 19.877390
2006-12-31 9.748760 29.069966 1.717175 3.283069 9.615215 25.787787
2007-12-31 29.772930 20.892030 16.597493 20.079373 17.320327 9.583089
2008-12-31 22.787891 26.636413 13.872783 29.305847 21.287553 1.263788
2009-12-31 1.574188 23.172773 0.967153 1.928999 12.201354 0.125939
2010-12-31 20.566125 0.429552 4.413156 16.106451 27.745684 18.280928
2011-12-31 9.348584 2.604338 23.397221 7.378340 16.757224 29.364973
2012-12-31 4.704570 7.278321 19.034622 24.597784 13.694635 15.912901
2013-12-31 21.657446 14.110146 23.976991 8.203509 20.083490 4.471119
2014-12-31 14.465823 9.105391 15.984162 6.796756 8.232619 18.761280
363 364 365
1995-12-31 28.165022 9.735041 NaN
1996-12-31 11.644543 4.139818 5.420238
1997-12-31 2.500165 18.290531 NaN
1998-12-31 23.856333 10.064951 NaN
1999-12-31 3.090008 26.203395 NaN
2000-12-31 22.216599 27.942821 0.791318
2001-12-31 25.682003 4.766435 NaN
2002-12-31 19.785159 28.972659 NaN
2003-12-31 15.692168 21.388069 NaN
2004-12-31 9.079675 7.392328 12.583179
2005-12-31 18.202333 21.895494 NaN
2006-12-31 20.951937 26.220226 NaN
2007-12-31 23.603166 28.165377 NaN
2008-12-31 20.532933 9.401494 25.296916
2009-12-31 5.879644 10.377044 NaN
2010-12-31 0.436284 20.875852 NaN
2011-12-31 13.205290 6.832805 NaN
2012-12-31 23.253155 17.760731 23.270751
2013-12-31 19.807798 2.453238 NaN
2014-12-31 12.817601 11.756561 NaN
[20 rows x 366 columns]

Categories

Resources