Python 将dict值重新映射到Pandas中的列
我有一个数据框,其中Python 将dict值重新映射到Pandas中的列,python,python-2.7,dictionary,pandas,Python,Python 2.7,Dictionary,Pandas,我有一个数据框,其中特性-列的值如下所示: dict示例: {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
特性
-列的值如下所示:
dict示例:
{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 {}
我认为您可以使用和:
如何处理
NaN
和{}
值df1=pd.DataFrame([x代表df中的x['FEATURES']如果是instance(x,dict)和x),index=df.index)
引发了一个错误值错误:传递值的形状是(17,66),索引暗示(17,105)是的,这是问题。一种解决方案是将NaN
替换为{}
-
features Cooking Type Specialty Cooking ... name price rating read reviews
9 {'Cooking...': '- S...', } Specialty Cooking Backyard ... Master Chef... $279.99 None None {}
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 {}