簡體   English   中英

將dict的pandas dataframe列展開為dataframe列

[英]Expand pandas dataframe column of dict into dataframe columns

我有一個 Pandas DataFrame,其中一列是一系列字典,如下所示:

   colA  colB                                  colC
0     7     7  {'foo': 185, 'bar': 182, 'baz': 148}
1     2     8  {'foo': 117, 'bar': 103, 'baz': 155}
2     5    10  {'foo': 165, 'bar': 184, 'baz': 170}
3     3     2  {'foo': 121, 'bar': 151, 'baz': 187}
4     5     5  {'foo': 137, 'bar': 199, 'baz': 108}

我希望字典中的foobarbaz鍵值對成為我的 dataframe 中的列,這樣我最終得到的是:

   colA  colB  foo  bar  baz
0     7     7  185  182  148
1     2     8  117  103  155
2     5    10  165  184  170
3     3     2  121  151  187
4     5     5  137  199  108

我怎么做?

TL; 博士

df = df.drop('colC', axis=1).join(pd.DataFrame(df.colC.values.tolist()))

詳細解答

我們首先定義要使用的 DataFrame 以及導入的 Pandas:

import pandas as pd


df = pd.DataFrame({'colA': {0: 7, 1: 2, 2: 5, 3: 3, 4: 5},
                   'colB': {0: 7, 1: 8, 2: 10, 3: 2, 4: 5},
                   'colC': {0: {'foo': 185, 'bar': 182, 'baz': 148},
                    1: {'foo': 117, 'bar': 103, 'baz': 155},
                    2: {'foo': 165, 'bar': 184, 'baz': 170},
                    3: {'foo': 121, 'bar': 151, 'baz': 187},
                    4: {'foo': 137, 'bar': 199, 'baz': 108}}})

colCpd.Series類型的字典中,我們可以把它變成一個pd.DataFrame通過轉動每個字典成pd.Series

pd.DataFrame(df.colC.values.tolist())
# df.colC.apply(pd.Series). # this also works, but it is slow

這給出了pd.DataFrame

   foo  bar  baz
0  154  190  171
1  152  130  164
2  165  125  109
3  153  128  174
4  135  157  188

所以我們需要做的就是:

  1. colC變成pd.DataFrame
  2. df刪除原始colC
  3. 使用df加入轉換colC

這可以在單行中完成:

df = df.drop('colC', axis=1).join(pd.DataFrame(df.colC.values.tolist()))

df的內容現在是pd.DataFrame

   colA  colB  foo  bar  baz
0     2     4  154  190  171
1     4    10  152  130  164
2     4    10  165  125  109
3     3     8  153  128  174
4    10     9  135  157  188

我最近遇到了同樣的挑戰,我設法使用applyjoin手動完成。

import pandas as pd

def expand_dict_column(df: pd.DataFrame, column) -> pd.DataFrame:
    df.drop(columns=[column], inplace=False).join(
        df.apply(lambda x: pd.Series(x[column].values(), index=x[column].keys()), axis=1))

對於問題的列,它看起來像這樣:

df.drop(columns=["colC"], inplace=False).join(
    df.apply(lambda x: pd.Series(x["colC"].values(), index=x["colC"].keys()), axis=1))

暫無
暫無

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

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