【问题标题】:Convert string with multiple values into a dict?将具有多个值的字符串转换为字典?
【发布时间】:2019-07-12 00:27:14
【问题描述】:

我有一个数据框,例如:

Path                          Attribute
/home/accessbile/wheelchair   type:threshold;width:42;gaurded:no
/home/accessible/wheelcahir   type:threshold;width:45
/home/accessbile/armchair     weight(lbs):100;width:30
/home/accessible/armchair     type:foldind;weight(lbs):100;width:30

我需要获取关于路径的值(类型、宽度、重量、gaurded 等)的属性中的唯一计数

输出:

    PATH                          Attributes  count


/home/accessbile/wheelchair     type          2
/home/accessbile/wheelchair     width         2
/home/accessbile/wheelchair    gaurded        1
/home/accessbile/armchair      weight(lbs)    2
/home/accessbile/armchair      width          2
/home/accessbile/armchair      type           1 

尝试通过ast.eval 将属性转换为dict,并将键作为唯一计数.. 但没有用

【问题讨论】:

    标签: python string pandas dictionary


    【解决方案1】:

    首先,检查Path中所有行的拼写,修复后,您可以执行以下操作:

    df.Attribute=df.Attribute.str.split(";")
    df_new=pd.DataFrame([[x] + [z] for x, y in df.values for z in y],columns=df.columns)
    df_new['Attribute']=df_new.Attribute.str.split(":").str[0]
    df_new.groupby('Path')['Attribute'].value_counts().reset_index(0).\
                   rename(columns={'Attribute':'Count'}).reset_index()
    
         Attribute                         Path  Count
    0         type  /home/accessbile/wheelchair      2
    1        width  /home/accessbile/wheelchair      2
    2      gaurded  /home/accessbile/wheelchair      1
    3  weight(lbs)    /home/accessible/armchair      2
    4        width    /home/accessible/armchair      2
    5         type    /home/accessible/armchair      1
    

    【讨论】:

      猜你喜欢
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      相关资源
      最近更新 更多