簡體   English   中英

Pandas - 從列中提取值

[英]Pandas - Extracting value from column

我有一個格式如下的 Dataframe。 我試圖將其分解為每個鍵值對的不同行。

id, data
101, [{'field': 'type1', 'newValue': '2020-01-16T12:35:50Z', 'oldValue': None}, 
      {'field': 'status', 'newValue': 'Started', 'oldValue': None}]

預期 output:

id, field, newValue, oldValue
101, type1, 2020-01-16T12:35:50Z, None
101, status, Started, None

讓我們在data上分解explode然后從分解的data列中創建一個新的 dataframe 最后使用join

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

你可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM