【发布时间】:2020-01-04 02:30:40
【问题描述】:
我必须为我的测量数据创建一个大字典。 到目前为止,我的(简化的)代码如下所示:
i = 0
for i in range(len(station_data_files_pandas)): # range(0, 299)
station_data_f_pandas = station_data_files_pandas[i]
station_id = str(int(station_data_f_pandas["STATIONS_ID"][0]))
Y_RR = station_data_f_pandas["MO_RR"].resample("A").apply(very_sum)
# creating the dictionary layer for the anual data in this dictionary
anual_data = {
"Y_RR" : Y_RR
}
# creating the dictionary layer for the montly data in this dictionary
montly_data = {
"MO_RR"
}
# creating the dictionary layer for every station. Everystation has montly and anual data
station = {
"montly_data" : montly_data,
"anual_data" : anual_data
}
# creating the dictionary layer where the staiondata can get called by station id
station_data_dic = {
station_id : station
}
# creating the final layer of the dictionary
station_data_dictionary = {
"station_data": station_data_dic
}
这是输出:
station_data_dictionary
Out[387]:
{'station_data': {'4706': {'montly_data': {'MO_RR'}, # "4706" is the id from the last element in station_data_files_pandas
'anual_data': {'Y_RR': YearMonth
# YearMonth is the index...
# I actually wanted the Index just to show yyyy-mm ...
1981-12-31 1164.3
1982-12-31 852.4
1983-12-31 826.5
1984-12-31 798.8
1985-12-31 NaN
1986-12-31 NaN
1987-12-31 NaN
1988-12-31 NaN
1989-12-31 NaN
1990-12-31 1101.1
1991-12-31 892.4
1992-12-31 802.1
1993-12-31 873.5
1994-12-31 842.7
1995-12-31 962.0
1996-12-31 NaN
1997-12-31 927.9
1998-12-31 NaN
1999-12-31 NaN
2000-12-31 997.8
2001-12-31 986.3
2002-12-31 1117.6
2003-12-31 690.8
2004-12-31 NaN
2005-12-31 NaN
2006-12-31 NaN
2007-12-31 NaN
2008-12-31 NaN
2009-12-31 NaN
2010-12-31 NaN
Freq: A-DEC, Name: MO_RR, dtype: float64}}}}
如您所见,我的输出仅包含一个“工作表”。预计为 300 张。
我假设我的代码在循环时会覆盖数据,因此最后我的输出只是由 station_data_files_pandas 中的最后一个元素组成的一张表。我怎样才能解决这个问题?我的方法可能完全错误吗?...
当它准备好时,它必须看起来像:
station_data_dictionary["station_data"]["403"]["anual_data"]["Y_RR"]
station_data_dictionary["station_data"]["573"]["anual_data"]["Y_RR"]
station_data_dictionary["station_data"]["96"]["anual_data"]["Y_RR"]
...等等。
如您所见,唯一允许我更改的就是我的 station_id,因为我在字典中称其为不同的东西。
注意:有一个问题的标题完全相同,但对我一点帮助都没有......
【问题讨论】:
-
在
for循环外创建station_data_dictionary,然后在循环内添加条目。 -
@Seb 谢谢你的回答。我已经尝试过这个,但我没有成功。你能告诉我如何在循环中添加条目吗?
-
你试过
station_data_files_pandas.to_dict()或station_data_files_pandas.to_json()吗?我不知道原始数据是什么样的,所以这些函数可能不相关。 -
@MarkMoretto 谢谢你的回答。 station_data_files_pandas 是 pandas 数据帧的列表。当您调用 station_data_files_pandas[0] 时,您会得到一个 pandas 数据帧。嗯,谢谢您的建议,但我认为,我不能使用快捷方式。
标签: python pandas loops for-loop