将值-字典重新映射到Pandas中的列 [英] Remap values-dict to columns in Pandas

查看:71
本文介绍了将值-字典重新映射到Pandas中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧,其中features列的值类似于dict,如下所示:

I have a dataframe where values of features-column are dict-like as here:

http://screencast.com/t/0Ko0NIBLwo

   features                    name             price  rating  read reviews
9  {'Cooking...': '- S...', }  Master Chef...  $279.99   None  None      {}  

字典示例:

{u'Cooking Type': u'- Specialty Cooking', u'Cooking Area': u'- Backyard', u'Brand Name': u'- Pizzacraft', u'Fuel Type': u'- Propane', u'Product Type': u'- BBQ', u'Size': u'- Medium Size'}

是否可以将这些值转换为新列?

Does it possible to transform these values to new columns like?

   features                    Cooking Type       Specialty Cooking  ... name             price  rating  read reviews
9  {'Cooking...': '- S...', }  Specialty Cooking   Backyard          ... Master Chef...    $279.99   None  None      {}  

推荐答案

我认为您可以使用 concat :

I think you can use replace and strip and concat:

print df
                                            features          name    price  \
0  {u'Cooking Type': u'- Specialty Cooking', u'Co...  Master Chef1  $279.99   
1  {u'Cooking Type': u'- Specialty Cooking', u'Co...  Master Chef3  $279.99   

  rating  read reviews  
0   None  None      {}  
1   None  None      {}  

df1 = pd.DataFrame([x for x in df['features']], index=df.index)

for col in df1.columns:
    df1[col] = df1[col].str.replace(r'-','').str.strip()

print df1
   Brand Name Cooking Area       Cooking Type Fuel Type Product Type  \
0  Pizzacraft     Backyard  Specialty Cooking   Propane          BBQ   
1  Pizzacraft     Backyard  Specialty Cooking   Propane          BBQ   

          Size  
0  Medium Size  
1  Medium Size  

df = pd.concat([df1, df[['name','price','rating','read','reviews']]], axis=1)
print df
   Brand Name Cooking Area       Cooking Type Fuel Type Product Type  \
0  Pizzacraft     Backyard  Specialty Cooking   Propane          BBQ   
1  Pizzacraft     Backyard  Specialty Cooking   Propane          BBQ   

          Size          name    price rating  read reviews  
0  Medium Size  Master Chef1  $279.99   None  None      {}  
1  Medium Size  Master Chef3  $279.99   None  None      {}  

这篇关于将值-字典重新映射到Pandas中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆