简体   繁体   English

取决于 Pandas Dataframe 列的值数组

[英]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.

相关问题 Pandas DataFrame:根据现有列的值检查将值写入列 - Pandas DataFrame: Writing values to column depending on a value check of existing column pandas-根据数据框的2个单独列中的值构造列 - pandas - construct column depending on values in 2 separate columns of dataframe 根据列的排序更改熊猫数据框中切片的值 - Change values from a slice in pandas dataframe depending on the sorting of a column 根据列值对有序pandas数据帧中的行进行分组 - group rows in ordered pandas dataframe depending on column values 如何根据多索引熊猫数据框中的行索引值创建列? - How to create a column depending on the row index values in a multiindex pandas dataframe? 更改 pandas dataframe 的一列中的值(应用)取决于此 dataframe 中其他列中的特定值与掩码 - Changing values (with apply) in one column of pandas dataframe depending on particular values in other column in this dataframe with mask 熊猫:生成一个数据框列,其值取决于数据框的另一列 - Pandas: Generate a Dataframe column which has values depending on another column of a dataframe 根据列值合并 2 dataframe - Merge 2 dataframe depending on column values 根据来自同一 pandas dataframe 的不同列中的值比较同一列的值 - Comparing values of same column depending on values in different column from the same pandas dataframe 检查列的值是否在熊猫数据框中的另一个列数组中 - Check if values of a column is in another column array in a pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM