data =
{'gems': [{'name': 'garnet', 'colour': 'red', 'month': 'January'},
{'name': 'emerald', 'colour': 'green', 'month': 'May'},
{'name': "cat's eye", 'colour': 'yellow', 'month': 'June'},
{'name': 'sardonyx', 'colour': 'red', 'month': 'August'},
{'name': 'peridot', 'colour': 'green', 'month': 'September'},
{'name': 'ruby', 'colour': 'red', 'month': 'December'}]}
我如何创建一个颜色列表,然后找到颜色为红色的月份?
我已经尝试和如果,但我一直得到错误信息
字符串索引必须是整数
因为列表中有字典,所以可以使用带有嵌套if逻辑的列表推导式来过滤掉那些不想要的值:
[x['month'] for x in data['gems'] if x['colour'] == 'red']
的回报:
['January', 'August', 'December']
假设要将输出作为数据帧,可以使用pandas.json_normalize
和pandas.DataFrame.query
如下所示
df = pd.json_normalize(data['gems']).query('colour == "red"')['month']
[Out]:
0 January
3 August
5 December
如果要重置索引,则需要将pandas.DataFrame.reset_index
传递为
df = pd.json_normalize(data['gems']).query('colour == "red"')['month'].reset_index(drop=True)
[Out]:
0 January
1 August
2 December