【发布时间】:2020-12-22 02:08:57
【问题描述】:
Year temp Name DateTime
1950 0 De Bilt 010100
1951 1 De Bilt 010100
1950 2 De Bilt 010101
1951 3 De Bilt 010101
1950 0 Arcen 010100
1951 1 Arcen 010100
我有这个数据框 (df_stations),并想用它创建一个 JSON,格式如下:
{
"De Bilt": {
"010100": {
"1950": {
"temp": 0
},
"1951": {
"temp": 1
}
},
"010101": {
"1950": {
"temp": 2
},
"1951": {
"temp": 3
}
}
},
"Arcen": {
"010100": {
"1950": {
"temp": 0
},
"1951": {
"temp": 1
}
},
...
但是,以下代码没有给我正确的结果:
def f(x):
return (dict({k:v for k,v in zip(x.DateTime,x.Year)},**{'temp':x.temp.iloc[0]}))
(
df_stations.groupby(['Name','DateTime','Year'])
.apply(f)
.groupby(level=0)
.apply(lambda x: x.tolist())
.to_dict()
)
有人可以帮我解决这个问题吗?非常感谢!
【问题讨论】:
-
你能举一个例子,数据框中的输入值对应于 JSON 中的输出值吗?当你有
De Bilt和Arcen在输出而不是输入,Voorschoten在输入而不是输出时,要准确理解你的目标有点困难。 -
感谢@MatějRačinský 的评论,我已更新数据框以与 JSON 相对应。