【问题标题】:Convert dataframe cell containing dictionary to dataframe with new columns pandas将包含字典的数据框单元格转换为具有新列 pandas 的数据框
【发布时间】:2020-10-09 05:09:27
【问题描述】:

这是数据框。其中包含一些单元格,其中包含字典。我想将字典项转换为列

dfx={'name':['Alex','Jin',np.nan,'Peter'],
     'age':[np.nan,10,12,13],
     'other':[{'school':'abc','subject':'xyz'},
     np.nan,
     {'school':'abc','subject':'xyz'},
     np.nan,]
     }

dfx=pd.DataFrame(dfx)

输出

name    age        other
Alex             {'school': 'abc', 'subject': 'xyz'}
Jin     10.0    
        12.0     {'school': 'abc', 'subject': 'xyz'}
Peter   13.0    

这是所需的输出

name    age      school    subject
Alex             abc         xyz
Jin     10.0        
        12.0     abc         xyz
Peter   13.0    

【问题讨论】:

  • 不会很快,所以如果你的框架很大我不推荐这个但你可以这样做dfx.join(dfx['other'].apply(pd.Series)).drop(columns=['other', 0])
  • 我正在尝试这种方式pd.DataFrame(list(dfx['other'].dropna())) 但它重置了索引,使其无法放回

标签: python pandas


【解决方案1】:

您可以使用.str.get 访问器来实际索引列中的字典。每当单元格值为nan 而不是字典时,这也会返回nan

clean_df = (dfx
            .assign(
               school=lambda df: df["other"].str.get("school"),
               subject=lambda df: df["other"].str.get("subject"))
            .drop("other", axis=1))

print(clean_df)
    name   age school subject
0   Alex   NaN    abc     xyz
1    Jin  10.0    NaN     NaN
2    NaN  12.0    abc     xyz
3  Peter  13.0    NaN     NaN

【讨论】:

    【解决方案2】:

    试试这个

    df_final = dfx[['name','age']].assign(**pd.DataFrame(dfx.other.to_dict()).T)
    
    Out[41]:
        name   age school subject
    0   Alex   NaN    abc     xyz
    1    Jin  10.0    NaN     NaN
    2    NaN  12.0    abc     xyz
    3  Peter  13.0    NaN     NaN
    

    【讨论】:

      【解决方案3】:

      创建dfx'sindexother 中的dictionarypd.DataFrame 字典和transpose。这会给你一个新的dataframe。将生成的 dataframe 加入 dfx 的前两列。

      dfx.iloc[:,:-1].join(pd.DataFrame(dict(zip(dfx.index,dfx.other))).T).fillna('')
      
      
      
          name age school subject
      0   Alex        abc     xyz
      1    Jin  10               
      2         12    abc     xyz
      3  Peter  13               
      

      【讨论】:

        【解决方案4】:

        您可以将Series 应用于带有字典的列:

        df.drop('other', 1).join(df['other'].apply(pd.Series).drop(0, 1))
        

        输出:

            name   age school subject
        0   Alex   NaN    abc     xyz
        1    Jin  10.0    NaN     NaN
        2    NaN  12.0    abc     xyz
        3  Peter  13.0    NaN     NaN
        

        【讨论】:

          猜你喜欢
          • 2019-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-12
          • 1970-01-01
          • 2019-02-22
          • 2017-07-16
          • 2020-12-22
          相关资源
          最近更新 更多