0

I have the following Pandas Dataframe:

Id         Values     Hour  
ES0024     4000       01:00
ES0024     5000       03:00
ES0024     6000       04:00
ES0024     7000       05:00
ES0024     8000       06:00
ES0024     9000       08:00

Want I want to do is to construct a json doc with the following output:

{"Id": "ES0024", "Values": [4000, None, 5000, 6000, 7000, 8000, None, 9000]}

So that if the corresponding position of the hour in the array of values is empty, a None value is entered.

Thank you very much!

2
  • Does this answer your question? pandas groupby to nested json Commented Nov 15, 2019 at 7:49
  • you could simply fill in the dataframe so it contains the values you need. you can resample using something like df.resample().fillna() Commented Nov 15, 2019 at 7:55

1 Answer 1

3

First try converting your DataFrame into required format and then convert it into dict. Maybe this will help you somewhere.

Get list of Hour with this first :

hour = list(pd.date_range("01:00", "08:00", freq="H").strftime('%H:%M'))

Hour List

Then set Hour and index and re-index with new Hour list obtained and finally reset index to get new DataFrame.

new_df = df.set_index("Hour").reindex(hour).reset_index()

new_df["Id"].fillna( method ='ffill', inplace = True)

Reformed DataFrame

And then convert it to dict to obtain similar results.

print(new_df.to_dict(orient='list'))

Dictionary

Though this is not the exact format you wanted, I think you should try it on your own after this.This will help you achieve it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.