17

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 column sezona_id and summing up the amount column kolicina.

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 season sezona_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
13
  • 8
    The title 'Resampling data frame dates to weeks and preserving data' and the question body you've included above don't ask any question I can discover. What was your question?
    – user11044402
    Jul 26, 2019 at 12:46
  • How to resample data frame from daily entries to weekly entries. I.e. grouping 7 days in a row to one entry. While preserving a season tag column.
    – Glorius
    Jul 26, 2019 at 12:48
  • 5
    Maybe your question should ask this question and not just present code and general call for help (with what?).
    – user11044402
    Jul 26, 2019 at 12:49
  • 8
    Some test data might have helped. If you can't share the actual data, share something representative instead. Then you can provide expected results and explain why they are the expected results. Jul 26, 2019 at 12:49
  • Good suggestions, didn't realise my actual question wasn't clear enough. I should have added representative data.
    – Glorius
    Jul 26, 2019 at 12:50
  • 9
    1) On the first glance it is unclear how the code is related. Only after reading the comments it's clear that you show failed attempts. I would split that int two parts: Data loading (which is working) and failed attempts. 2) I would translate everything to english. It's important to understand how your data is structured, but I can't interfere that from grupa_naziv or kolicina. 3) You have to provide an input data sample (can be made up, no need for the real data) and an expected output.
    – BDL
    Jul 26, 2019 at 12:54
  • Very well BDL..
    – Glorius
    Jul 26, 2019 at 12:59
  • 1
    By the way: to notify another user in a comment you need to write an "@" in front of their name. That will even give you an autocomplete option once you have typed a few letters of the users name. The author of a post is always notified of a comment.
    – Secespitus
    Jul 26, 2019 at 13:18
  • 7
    Nit pick: There is no need for "Any help is much appreciated". This is just fluff/noise. Just focus on the content.
    – honk
    Jul 26, 2019 at 13:25
  • BDL hit the major points I would make. On top of that the line breaks in the code are showing up in really weird places. Not sure if the original post is like that or something got garbled pasting to here, but in either case double check your formatting.
    – user2201041
    Jul 26, 2019 at 21:17
  • @jonrsharpe What's up with edit 2? Did the OP originally put his code inside comments in his now-deleted question and is now showing us a cleaned-up version -- or did an error in editing occur in edit 2? Do you have a link to the deleted question? I'm curious. An edit comment like "this is the original formatting" could have cleared that up and so I just don't know.
    – Paul
    Jul 27, 2019 at 1:02
  • @Paul I was just clarifying visually which parts of this question were the referred-to question (and answer), although it looks like the auto-quote broke the code fence without me noticing...
    – jonrsharpe
    Jul 27, 2019 at 7:09
  • @jonrsharpe Thanks for clarifying that. Glad its fixed now, so I could fix my part -- mostly by deleting lots of rant about how horrible it is to put all the code in comments.
    – Paul
    Jul 27, 2019 at 8:32

1 Answer 1

16

To improve, generally:

Focus on your writing from the viewpoint of a volunteer reading it who has some experience or expertise and is willing to help but is also busy. This kind of empathy is difficult when you are busy, overworked, tired, and simply need an answer while you attend to something else.

Would you want to answer this question? Is everything there ready for you to do so, and easy to read? Really? Read it again. I find it hard to write anything that doesn't require some editing, even editing multiple times. Is it incomplete? How much work would it be for the reader to fix it or fill in unclear pieces?

This Question

The question is sloppy and is not a minimal complete verifiable example. If you are asking about a bug or error, that's enough to put the question "on hold". The question is possibly "too broad" for some people because it never pins down a very specific question but dances around several lines of code that don't work. "Unclear what you are asking" is a more succinct criticism (mentioned by at least one comment) and also a standard reason to put a question "on hold". Some people will simply downvote such questions because they also satisfy the downvote criteria that pop up when you mouse over the down arrow.

It suffers from a balance-of-work issue. The visitors who are willing to answer questions can not be expected to do 90+% of the work (invent fake data, take your notes and write actual shared runnable code that is compatible with the fake data, actual tests, find the bug, explain it to you, provide correct code). The requirement of a minimal, complete, verifiable example, would require you to first create actual code and some "fake" data that demonstrates the problem. This provides data, actual shared runnable code, and an actual test; and would require a helpful visitor to find the bug, explain it to you, and/or provide correct code. That's a better distribution of work between the question and answer.

Sometimes it seems the name of the site, "Stack Overflow", causes people to think the site exists to help people who are in a state of work overflow together with all the related social and communications symptoms of being overworked. Because they are busy/overworked, they do a brain dump and/or code dump here and hope to get rational answers and/or code back. Instead it can be "Garbage In, Garbage Out" and everyone will be like :-(

Specific content issues while reading the original post

  • What are the inputs/outputs/error messages? Unclear.

  • What were you trying to accomplish? Partially explained.

  • What happened instead? Partially explained in brief code comments.

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 column sezona_id and summing up the amount column kolicina.

This is not nearly clear enough. Please note that I don't want to engage in correspondence to determine the answers to questions below, but mention them so that you can see what I don't know.

Resample to weeks from what? days? dates? Unix time stamps?

What needs to preserved and how? What needs to be summed? What other columns are there? Are they aggregated in some other way?

It would be better to provide a short excerpt of "fake input data" and the desired "fake output data" because a concrete simple example (or a short list of examples) often answers a number of abstract questions about the procedure.

3
  • Thank you for your insight! I must point out, however, that criticisms 2, 3 and 4 are not applicable to this case since they are a result of @johnrshapre's edit (which he has now fixed). I will add screenshots of the question and answer shortly.
    – Glorius
    Jul 27, 2019 at 7:51
  • @DominikAgejev I agree and deleted those critiques. Good luck improving your posts.
    – Paul
    Jul 27, 2019 at 8:21
  • Thank you. Hopefully all of my questions are spotted by such a good author.
    – Glorius
    Jul 27, 2019 at 8:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .