[英]How to extract the Dictionary value inside the List in the column, Pandas?
[英]Extract dictionary value from a list with one element in a pandas column
我有一個 pandas dataframe ,其中有一列是包含單個字典的列表。 例如:
col1
[{'type': 'yellow', 'id': 2, ...}]
[{'type': 'brown', 'id': 13, ...}]
...
我需要提取與“類型”關鍵字關聯的值。 有不同的方法可以做到這一點,但由於我的 dataframe 很大(數百萬行),我需要一種有效的方法來做到這一點,但我不確定哪種方法最好。
讓我們試試這個:
data = {
'col': [[{'type': 'yellow', 'id': 2}], [{'type': 'brown', 'id': 13}], np.nan]
}
df = pd.DataFrame(data)
print(df)
col
0 [{'type': 'yellow', 'id': 2}]
1 [{'type': 'brown', 'id': 13}]
2 NaN
使用explode
和str
訪問器:
df['result'] = df.col.explode().str['type']
output:
col result
0 [{'type': 'yellow', 'id': 2}] yellow
1 [{'type': 'brown', 'id': 13}] brown
2 NaN NaN
訪問大多數數據結構中的任何元素都是 O(1) 操作。 我確定 pandas 數據幀也不例外。 您將面臨的唯一問題是:循環遍歷行。 可能沒有辦法解決它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.