【问题标题】:Pandas list of JSON element to python arrayJSON元素的熊猫列表到python数组
【发布时间】:2022-11-02 03:12:10
【问题描述】:

我有一个像这样的数据框:

Store matches
Murphy's [{'domain': 'murphyscolumbus.com', 'location': 'Columbus, OH'}, {'domain': 'murphystampa.com', 'location': 'Tampa, FL'}]
Bill's [{'domain': 'billsdallas.com', 'location': 'Dallas, TX'}, {'domain': 'billsorlando.com', 'location': 'Orlando, FL'}]

我想要的是这样的数据框:

Store domains
Murphy's ['murphyscolumbus.com', 'murphystampa.com']
Bill's ['billsdallas.com','billsorlando.com']

我希望在计算上比像 for 循环这样的东西更便宜,因为数据框是逐步通过的相当大的。

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    尝试:

    from ast import literal_eval
    
    # apply literal_eval if necessary
    df["matches"] = df["matches"].apply(literal_eval)
    
    df["domains"] = df.pop("matches").apply(lambda x: [d["domain"] for d in x])
    print(df)
    

    印刷:

          Store                                  domains
    0  Murphy's  [murphyscolumbus.com, murphystampa.com]
    1    Bill's      [billsdallas.com, billsorlando.com]
    

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2022-07-11
      相关资源
      最近更新 更多