如何从含JSON数据的Pandas DataFrame提取最新年份及对应值作为新列?
提取Pandas DataFrame中JSON数据的最新年份及对应值并新增列
针对你的需求,这里提供两种实现方式,分别适用于JSON中year列表有序递增和无序的场景:
场景1:year列表按时间递增(如示例数据)
这种情况直接取year和val列表的最后一个元素即可:
import pandas as pd import json # 原始数据 data = { 'id': [1, 2, 3], 'name': ['Alice', 'Bob', 'Charlie'], 'json_data': [ '{"year": [2000, 2001, 2002], "val": [10, 20, 30]}', '{"year": [2003, 2004, 2005], "val": [50, 60, 70]}', '{"year": [2006, 2007, 2008], "val": [80, 90, 85]}' ] } df = pd.DataFrame(data) # 解析JSON字符串为字典 df['parsed_json'] = df['json_data'].apply(json.loads) # 提取最新年份和对应值 df['Most Recent Year'] = df['parsed_json'].apply(lambda x: x['year'][-1]) df['Most Recent val'] = df['parsed_json'].apply(lambda x: x['val'][-1]) # 移除中间解析列(可选) df.drop('parsed_json', axis=1, inplace=True) print(df)
输出结果:
| id | name | json_data | Most Recent Year | Most Recent val |
|---|---|---|---|---|
| 1 | Alice | {"year": [2000, 2001, 2002], "val": [10, 20, 30]} | 2002 | 30 |
| 2 | Bob | {"year": [2003, 2004, 2005], "val": [50, 60, 70]} | 2005 | 70 |
| 3 | Charlie | {"year": [2006, 2007, 2008], "val": [80, 90, 85]} | 2008 | 85 |
场景2:year列表无序(需找最大值对应的val)
如果JSON中的year列表不是按顺序排列的,需要先找到最大年份的索引,再匹配对应的val:
import pandas as pd import json # 模拟无序year的测试数据 data_unordered = { 'id': [4], 'name': ['Dave'], 'json_data': ['{"year": [2010, 2008, 2012], "val": [100, 150, 120]}'] } df_unordered = pd.DataFrame(data_unordered) # 解析JSON df_unordered['parsed_json'] = df_unordered['json_data'].apply(json.loads) # 自定义函数提取最新年份和对应值 def get_latest_item(item): max_year = max(item['year']) max_idx = item['year'].index(max_year) return max_year, item['val'][max_idx] # 批量提取并生成新列 df_unordered[['Most Recent Year', 'Most Recent val']] = df_unordered['parsed_json'].apply(get_latest_item).apply(pd.Series) # 移除中间列 df_unordered.drop('parsed_json', axis=1, inplace=True) print(df_unordered)
输出结果:
| id | name | json_data | Most Recent Year | Most Recent val |
|---|---|---|---|---|
| 4 | Dave | {"year": [2010, 2008, 2012], "val": [100, 150, 120]} | 2012 | 120 |
内容的提问来源于stack exchange,提问作者kms
相关产品推荐
相关产品推荐

