python - 将 value-dict 重新映射到 Pandas 中的列

标签 python python-2.7 dictionary pandas

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

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'}

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

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

最佳答案

我认为你可以使用replacestripconcat :

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      {}  

关于python - 将 value-dict 重新映射到 Pandas 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35628640/

相关文章:

python - django 多选浏览器按钮,形式类似于 html

python - Selenium 在一段时间后停止工作

python - 如何将 Python 元组转换为 .csv 文件?

python - 在 python 中排序字典列表

c# - 使用 LINQ 将 List<int> 转换为 Dictionary<int,int>

python - 保证找到四个单色点的最小 k X l 网格

python - 模拟父类 __init__ 方法

python-2.7 - 创建并使用内置 int 数据类型的 NumPy 数组

r - 将世界地图分为特定国家/地区的面板

python - 如何将具有非 ASCII 字节的字节数组转换为 python 中的字符串?