将具有多个值的字符串转换为dict?

2024-10-04 05:29:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,例如:

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

我需要在属性中获取关于路径的值(type、width、weight、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,并将键作为唯一计数。。但不起作用


Tags: 数据pathhomethreshold属性typewidth计数
1条回答
网友
1楼 · 发布于 2024-10-04 05:29:10

首先,检查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

相关问题 更多 >