[英]Array of values depending on column of Pandas Dataframe
I have the following Pandas Dataframe:我有以下 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:我想做的是用以下 output 构建一个 json 文档:
{"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.因此,如果值数组中对应的小时的 position 为空,则输入 None 值。
Thank you very much!非常感谢!
First try converting your DataFrame into required format and then convert it into dict.首先尝试将您的 DataFrame 转换为所需的格式,然后将其转换为 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'))
Then set Hour and index and re-index with new Hour list obtained and finally reset index to get new DataFrame.然后设置 Hour 和 index 并使用获得的新 Hour 列表重新索引,最后重置索引以获得新的 DataFrame。
new_df = df.set_index("Hour").reindex(hour).reset_index()
new_df["Id"].fillna( method ='ffill', inplace = True)
And then convert it to dict to obtain similar results.然后将其转换为 dict 以获得类似的结果。
print(new_df.to_dict(orient='list'))
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.虽然这不是您想要的确切格式,但我认为您应该在此之后自行尝试。这将帮助您实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.