Python:如何按季度条件将JSON数据分配至对应变量?
按季度分组提取JSON数据并分配到对应变量
需求说明
从JSON文件中根据日期所属季度提取数据,将对应数据分别存入Q1、Q2、Q3、Q4变量,每个变量需保留包含lastDate、transactionType、sharesTraded的结构化数据,仅保留对应季度的条目。
原始JSON数据
{ "lastDate":{ "0":"2022Q4", "1":"2022Q4", "2":"2022Q4", "7":"2022Q4", "8":"2022Q4", "9":"2022Q4", "18":"2022Q3", "19":"2022Q3", "22":"2022Q3", "24":"2022Q2" }, "transactionType":{ "0":"Sell", "1":"Automatic Sell", "2":"Automatic Sell", "7":"Automatic Sell", "8":"Sell", "9":"Automatic Sell", "18":"Automatic Sell", "19":"Automatic Sell", "22":"Automatic Sell", "24":"Automatic Sell" }, "sharesTraded":{ "0":"20,200", "1":"176,299", "2":"8,053", "7":"167,889", "8":"13,250", "9":"176,299", "18":"96,735", "19":"15,366", "22":"25,000", "24":"25,000" } }
错误代码及问题
尝试的代码如下,运行后输出为空列表[],无法得到预期的结构化数据:
import json data = json.load(open("AAPL22data.json")) Q2data = [item for item in data if '2022Q2' in data['lastDate']] print(Q2data)
问题分析
- 列表推导式遍历的是
data的键(lastDate、transactionType、sharesTraded),而非数据条目。 - 条件判断
'2022Q2' in data['lastDate']是检查字符串是否存在于lastDate的键中,但2022Q2是lastDate的值,导致条件永远不成立。
解决方案
先按季度分组记录对应的条目索引,再根据索引构建每个季度的结构化数据:
import json # 加载JSON文件(使用with语句确保文件正确关闭) with open("AAPL22data.json", "r") as f: data = json.load(f) # 初始化季度分组,存储对应条目的索引 quarter_indices = { "Q1": [], "Q2": [], "Q3": [], "Q4": [] } # 遍历lastDate,按季度归类索引 for idx, quarter_str in data["lastDate"].items(): # 提取季度标识(如"2022Q4"中的"Q4") quarter_tag = quarter_str[-2:] if quarter_tag in quarter_indices: quarter_indices[quarter_tag].append(idx) # 生成指定季度的结构化数据 def get_quarter_data(indices): return { "lastDate": {idx: data["lastDate"][idx] for idx in indices}, "transactionType": {idx: data["transactionType"][idx] for idx in indices}, "sharesTraded": {idx: data["sharesTraded"][idx] for idx in indices} } # 分配各季度数据到对应变量 Q1 = get_quarter_data(quarter_indices["Q1"]) Q2 = get_quarter_data(quarter_indices["Q2"]) Q3 = get_quarter_data(quarter_indices["Q3"]) Q4 = get_quarter_data(quarter_indices["Q4"]) # 示例:打印Q2数据 print(json.dumps(Q2, indent=4))
运行结果
Q2变量的输出符合预期:
{ "lastDate": { "24": "2022Q2" }, "transactionType": { "24": "Automatic Sell" }, "sharesTraded": { "24": "25,000" } }
内容的提问来源于stack exchange,提问作者kiestuthridge23
相关产品推荐
相关产品推荐

