import pandas as pd
data = {'Product Description': [': da t?ng h?p, khung g? s?i canada.', ': g? mfc ph? melamine, chan 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 'chan 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']]}
謝謝你。
uj5u.com熱心網友回復:
你快到了。在您的add_material函式中,您遍歷產品描述字串中的每個字符,因此您沒有匹配項。
import pandas as pd
data = {'Product Description': [': da t?ng h?p, khung g? s?i canada.', ': g? mfc ph? melamine, chan 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 'chan 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, chan thép s?n t?nh [Melamine coated MFC Wood, Steel]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/353106.html
