首页 > 解决方案 > Pandas 数据框将字符串拆分为具有条件和缺失数据的多列

问题描述

所以我有一个看起来像这样的 DataFrame:

df = pd.DataFrame({'feature1':[34,45,52],'feature2':[1,0,1],'unparsed_features':["neoclassical, heavy, $2, old, bronze", "romanticism, gold, $5", "baroque, xs, $3, new"]})

df
       feature1  feature2                     unparsed_features
    0        34         1  neoclassical, heavy, $2, old, bronze
    1        45         0                 romanticism, gold, $5
    2        52         1                  baroque, xs, $3, new

我正在尝试将该列拆分unparsed_features为 6 列(重量、年龄、颜色、尺寸、价格和期限),但正如您所见,订单混乱不堪,不仅如此,还缺少一些字段。

我大致了解每列可能是什么,如下所示:

main_dict = {
 'weight': ['heavy','light'],
 'age': ['new','old'],
 'colour': ['gold','silver','bronze'],
 'size': ['xs','s','m','l','xl','xxl','xxxl'],
 'price': ['$'],
 'period': ['renaissance','baroque','rococo','neoclassical','romanticism']
}

理想情况下,我希望我的 Dataframe 如下所示:

df
   feature1  feature2                     unparsed_features weight price  age  \
0        34         1  neoclassical, heavy, $2, old, bronze  heavy    $2  old   
1        45         0                 romanticism, gold, $5           $5        
2        52         1                  baroque, xs, $3, new           $3  new   

  size  colour        period  
0       bronze  neoclassical  
1         gold   romanticism  
2   xs               baroque

我知道第一步是用逗号分割字符串,但在那之后我迷路了。

df['unparsed_features'].str.split(',')

谢谢您的帮助。

标签: pythonstringpandasdataframe

解决方案


坦率地说,WB 是正确的,你需要修改你的 dict,但是用下面的可用数据来解决是我的方法

for keys in main_dict:
    data_list = []
    for value in df.unparsed_features: # for every row
        for l_data in main_dict[keys]:
            if keys == 'price':
                matching = [v for v in value.split(',') if l_data in v]
            else:
                matching = [v for v in value.split(',') if l_data == v.strip()]

            if matching:
                break

        if matching:
            data_list.append(matching[0])
        else:
            data_list.append(None)

        matching = ''  
    df[keys] = data_list

输出

   feature1  feature2                     unparsed_features  weight   age  \
0        34         1  neoclassical, heavy, $2, old, bronze   heavy   old   
1        45         0                 romanticism, gold, $5    None  None   
2        52         1                  baroque, xs, $3, new    None   new   

    colour  size price        period  
0   bronze  None    $2  neoclassical  
1     gold  None    $5   romanticism  
2     None    xs    $3       baroque  

推荐阅读