簡體   English   中英

將字典鍵和值轉換為行和列

[英]Convert dictionary keys and values into rows and columns

我有一個包含多行的字典列表。 我需要將鍵存儲為列,將值存儲為行。

    date        model
    22/01/2022  [{'vehicles': {'engine': 0, 'status': 5, 'size': 0, 'warranty': 2, 'type': 3, }}]
    .
    .
    .
    23/01/2022  [{'vehicles': {'engine': 3, 'status': 4, 'size': 1, 'warranty': 5, 'type': 1, }}]

df = pd.DataFrame.from_dict(df["model"]['vehicles'], orient="columns")

我厭倦了 select 的值,但它不起作用。

df = pd.DataFrame({'date': ['22/01/2022', '23/01/2022'], 'model': [[{'vehicles': {'engine': 0, 'status': 5, 'size': 0, 'warranty': 2, 'type': 3, }}], [{'vehicles': {'engine': 3, 'status': 4, 'size': 1, 'warranty': 5, 'type': 1, }}]]})
df = df.explode('model')
df.model = [m['vehicles'] for m in df.model]
pd.concat([df, df.model.apply(pd.Series)], axis=1).drop('model', axis=1)

Output:

         date  engine  status  size  warranty  type
0  22/01/2022       0       5     0         2     3
1  23/01/2022       3       4     1         5     1

暫無
暫無

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

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