【问题标题】:How to add many specific string from a string to a list in columns?如何将字符串中的许多特定字符串添加到列中的列表中?
【发布时间】:2021-12-21 00:17:04
【问题描述】:
import pandas as pd
data = {'Product Description': [': da tổng hợp, khung gỗ sồi canada.', ': gỗ mfc phủ melamine, chân thép sơn tĩnh']}
df = pd.DataFrame(data)
def add_material(row):
    lst = []   
    temp = row['Product Description'] 
    for i in temp:
        if 'da tổng hợp' in temp:
            lst.append('Synthetic Leather')
        elif 'gỗ sồi' in temp:
            lst.append('Oak')
        elif 'gỗ mfc phủ melamine' in temp:
            lst.append('Melamine coated MFC Wood')
        elif 'chân thép' in temp:
            lst.append('Steel')
        return lst
        continue
    
df['Material'] = df.apply(add_material, axis = 1)

“材料”列中的列表不包含第二种材料。我想要这样的第二列:

cols_2 = {'Material': [['Synthetic Leather', 'Oak'], ['Melamine coated MFC Wood', 'Steel']]}

谢谢。

【问题讨论】:

    标签: python pandas string list


    【解决方案1】:

    你快到了。在您的 add_material 函数中,您遍历产品描述字符串中的每个字符,因此您找不到匹配项。

    import pandas as pd
    data = {'Product Description': [': da tổng hợp, khung gỗ sồi canada.', ': gỗ mfc phủ melamine, chân thép sơn tĩnh']}
    df = pd.DataFrame(data)
    
    def add_material(x):
        lst = []
        if 'da tổng hợp' in x:
            lst.append('Synthetic Leather')
        if 'gỗ sồi' in x:
            lst.append('Oak')
        if 'gỗ mfc phủ melamine' in x:
            lst.append('Melamine coated MFC Wood')
        if 'chân thép' in x:
            lst.append('Steel')
        return lst
    
    df['Material'] = df["Product Description"].apply(add_material)
    
    

    然后你得到

    >>> df
                             Product Description                           Material
    0        : da tổng hợp, khung gỗ sồi canada.           [Synthetic Leather, Oak]
    1  : gỗ mfc phủ melamine, chân thép sơn tĩnh  [Melamine coated MFC Wood, Steel]
    

    【讨论】:

      猜你喜欢
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 2022-06-12
      • 2020-03-08
      • 2011-06-16
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      相关资源
      最近更新 更多