Python Pandas-从列中提取值
我有一个以下格式的数据帧。我正在尝试将每个键值对分成不同的行Python Pandas-从列中提取值,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个以下格式的数据帧。我正在尝试将每个键值对分成不同的行 id, data 101, [{'field': 'type1', 'newValue': '2020-01-16T12:35:50Z', 'oldValue': None}, {'field': 'status', 'newValue': 'Started', 'oldValue': None}] 预期产出: id, field, newValue, oldValue 101, type1, 2020-01-16T1
id, data
101, [{'field': 'type1', 'newValue': '2020-01-16T12:35:50Z', 'oldValue': None},
{'field': 'status', 'newValue': 'Started', 'oldValue': None}]
预期产出:
id, field, newValue, oldValue
101, type1, 2020-01-16T12:35:50Z, None
101, status, Started, None
您可以这样做:
In [4432]: df = pd.DataFrame({'id':[101], 'data':[[{'field': 'type1', 'newValue': '2020-01-16T12:35:50Z', 'oldValue': None}, {'field': 'status', 'newValue': 'Started', 'oldValue': None}]]})
In [4438]: df1 = df.explode('data')['data'].apply(pd.Series)
In [4440]: df = pd.concat([df.id, df1], axis=1)
In [4441]: df
Out[4441]:
id field newValue oldValue
0 101 type1 2020-01-16T12:35:50Z None
0 101 status Started None
让我们分解
数据
上的数据框,然后从分解的数据
列创建一个新的数据框,最后使用连接
:
out = df.explode('data').reset_index(drop=True)
out = out.join(pd.DataFrame(out.pop('data').tolist()))
谢谢你的帮助。。
print(out)
id field newValue oldValue
0 101 type1 2020-01-16T12:35:50Z None
1 101 status Started None