My questions consistently fare badly on Stack Overflow. Although my account was created a while ago, I only just started using SO.
My most recent question got 3 downvotes of just 16 views before I deleted it.
I almost always try and research a lot before posting a question of my own. I try my best to provide elaborate context right from the start even though my questions have simple solutions in the end.
Here is my latest and apparently worst question. I hope some of you can tell me why you would downvote it, what's good in it and what's bad.
Resampling data frame dates to weeks and preserving data
For a while now I have been trying to resample my data frame to weeks based on a date column
dan_id
while preserving/forward-filling a season tag columnsezona_id
and summing up the amount columnkolicina
.Here is my code (unfortunately I am unable to share the data):
# Libraries import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.dates as mdates from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() # Import data data = pd.read_excel(r'C:\Users\dagejev\Downloads\export_20190719.xls', index_col=26) # Creating list of unique group names groups = data.reset_index()['grupa_naziv'].unique() groups.sort() # Modifying data data2 = data.copy() data2 = data2[['sezona_id','dan_id','kolicina']] data2 = data2[data2['kolicina'] >= 0] #-Convert time column to datetime data2['dan_id'].apply(str) data2['dan_id'] = data2['dan_id'].apply(pd.to_datetime, format='%Y%m%d') #-More modifying data data2 = data2.reset_index().set_index('sezona_id') data2.drop(index=['NNN','COV','NOS'],inplace=True) data2 = data2.reset_index().groupby(['grupa_naziv', 'sezona_id', 'dan_id']).agg({'kolicina':'sum'}).reset_index() data2 = data2.reset_index().set_index('grupa_naziv').sort_index() # Limiting data to one group BERMUDE = data2.loc[groups[0]].reset_index().set_index(['sezona_id','dan_id']).sort_index().drop(['index','grupa_naziv'],axis='columns') # Failed attempts to present weekly data logic = {'sezona_id': lambda x: x, 'kolicina' : lambda x: x} # Runs and messes up ordering resulting in loss of data '''BERMUDE = BERMUDE.resample('W').apply(logic) BERMUDE = BERMUDE.where(BERMUDE['kolicina'] > 0).dropna()''' # Runs and does nothing '''(BERMUDE.reset_index().groupby(pd.Grouper(key='dan_id',freq='W',axis=1)) .agg(logic)) ''' # Runs and just groups by sezona_id, doesn't group by week def resampler(x): return x.set_index('dan_id').resample('W') BERMUDE.reset_index(level=1).groupby(level=0).apply(resampler)
This data will be used for plotting a line graph for each group with
kolicina
on the y-axis, weeks on the x-axis and one line for each seasonsezona_id
Any help is much appreciated.
I followed up the post with an answer of my own 7 minutes after I posted the question (which probably makes it seem I posted the question before researching but that is not the case).
Found a solution:
def group_by_week(df): level_values = df.index.get_level_values return (df.groupby([level_values(0)] +[pd.Grouper(freq='W', level=-1)]).sum()) print(group_by_week(BERMUDE))
Outputs:
kolicina sezona_id dan_id S17 2017-04-02 1 2017-04-30 1 2017-05-07 1 2017-05-21 7 2017-05-28 4 2017-06-04 3 S18 2018-03-11 1 2018-05-20 2 2018-05-27 2
grupa_naziv
orkolicina
. 3) You have to provide an input data sample (can be made up, no need for the real data) and an expected output.