【问题标题】:Extraction of array list values in pandas dataframe在熊猫数据框中提取数组列表值
【发布时间】:2022-11-13 19:08:36
【问题描述】:

我有一个名为“方法”的数据框列,如下所示:

`

array(["{'get': 12, 'post': 4, 'put': 1, 'delete': 1, 'patch': 0, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0}",
       "{'get': 13, 'post': 4, 'put': 1, 'delete': 1, 'patch': 0, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0}",
       "{'get': 3, 'post': 1, 'put': 2, 'delete': 1, 'patch': 1, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0, 'parameters': {'$numberDouble': 'NaN'}}",
       ...,
       "{'get': 3, 'post': 6, 'put': 0, 'delete': 2, 'patch': 2, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0, 'parameters': {'$numberDouble': 'NaN'}}",
       "{'get': 4, 'post': 1, 'put': 3, 'delete': 1, 'patch': 0, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0}",
       "{'get': 3, 'post': 3, 'put': 3, 'delete': 3, 'patch': 0, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0, 'parameters': {'$numberDouble': 'NaN'}}"],
      dtype=object)

我想提取不同数据框中的值,例如获取、发布、将它们的值放在下面。实现这一目标的最佳方法是什么?

我尝试使用eval() function 和类似的东西`

df1 = df.pop('methods').str.strip('{').str.split(':',expand=True).astype(float)

但也没有工作。有什么建议我应该改用吗?

【问题讨论】:

    标签: python arrays pandas


    【解决方案1】:

    你可以试试:

    df = pd.DataFrame({'methods':array})
    
    df['methods'] = df['methods'].agg(eval)
    df = pd.concat([df, df['methods'].agg(pd.Series)], axis=1) 
    

    输出:

    methods                                                  get    post put    delete  patch   head    options trace   connect parameters
    0   {'get': 12, 'post': 4, 'put': 1, 'delete': 1, ...   12.0    4.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 NaN
    1   {'get': 13, 'post': 4, 'put': 1, 'delete': 1, ...   13.0    4.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 NaN
    2   {'get': 3, 'post': 1, 'put': 2, 'delete': 1, '...   3.0 1.0 2.0 1.0 1.0 0.0 0.0 0.0 0.0 {'$numberDouble': 'NaN'}
    3   {'get': 3, 'post': 6, 'put': 0, 'delete': 2, '...   3.0 6.0 0.0 2.0 2.0 0.0 0.0 0.0 0.0 {'$numberDouble': 'NaN'}
    4   {'get': 4, 'post': 1, 'put': 3, 'delete': 1, '...   4.0 1.0 3.0 1.0 0.0 0.0 0.0 0.0 0.0 NaN
    5   {'get': 3, 'post': 3, 'put': 3, 'delete': 3, '...   3.0 3.0 3.0 3.0 0.0 0.0 0.0 0.0 0.0 {'$numberDouble': 'NaN'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 2016-08-09
      • 2022-01-23
      • 2022-01-11
      • 2022-07-22
      相关资源
      最近更新 更多