【发布时间】:2019-01-21 15:42:07
【问题描述】:
我的代码一直有问题,我不确定我还能做什么。我想从产品标题中删除所有变体。其中一些正在被删除,而另一些则没有。 未删除的示例是 oz、ml、mg 和 new_words_filtered csv 文件中的许多单词。 我不确定我可以采取哪些其他方法来完成这项任务,我在想正则表达式,但我不知道产品名称的所有模式都进来了,或者可能使用模糊匹配来找到最长的匹配字符串。
只是关于数据的一点点,15,000+ 它们都是包含颜色、尺寸、包装等变体的产品标题。 它们的长度、格式不同,有些拼写和间距不正确。
我希望有人可以看看我的代码,也许可以告诉我我做错了什么或有任何其他方法来解决这个问题。
`import pandas as pd
import time
#file_name= 'new_london.csv'
file_name= 'london.csv'
words_filtered = 'new_words_filtered.csv'
colors = 'more_colors.csv'
df = pd.read_csv(file_name, header=None,
names=range(150))
colors_df = pd.read_csv(colors)
words_filtered_df = pd.read_csv(words_filtered)
def filter_lists(x):
x = str(x).strip()
x = " ".join(x.split())
if x.endswith('/'):
x = x[:-1].strip()
if x.endswith('.'):
x = x[:-1].strip()
if x.endswith('/'):
x = x[:-1].strip()
x = x.strip()
if len(x) < 2:
return ''
return x.lower()
colors_df = colors_df.applymap(filter_lists)
colors_df.drop_duplicates(inplace=True)
colors_df.dropna(inplace=True)
colors= list(set([ str(i[0]) for i in
colors_df.values.tolist()]))
colors.append('vanilla')
words_filtered_df.dropna(axis=1, how='all', inplace=True)
words_filtered_df =
words_filtered_df.applymap(filter_lists)
words_filtered_df.drop_duplicates(inplace=True)
words_filtered = set([ str(i[0]) for i in
words_filtered_df.values.tolist()])
words_filtered.remove('')
words_filtered = list(words_filtered)
df.columns = df.iloc[0]
df = df.drop(df.index[[0]])
df.fillna('', inplace=True)
d = df['name']
def filter_data_new(x):
x = x.lower().strip()
x = " ".join(x.split())
x = x.strip()
if x.endswith('.'):
x = x[:-1]
x = x.strip()
if x.endswith('/'):
x = x[:-1]
x = x.strip()
if x.endswith('.'):
x = x[:-1]
x = x.strip()
for i in colors:
if x.endswith(i):
l = len(i)
x = x[:-l]
x = x.strip()
x = x.strip().split('-')
x = "-".join([i.strip() for i in x if len(i.strip())])
for i in words_filtered:
if x.endswith(i):
x = x.strip()
l = len(i)
x = x[:-l]
x = x.strip()
break
x = x.strip().split('-')
x = "-".join([i for i in x if len(i.strip())])
for i in words_filtered:
if x.endswith(i):
x = x.strip()
l = len(i)
x = x[:-l]
x = x.strip()
break
x = x.strip().split('-')
x = " -".join([i for i in x if len(i.strip())])
if x.endswith('oz') or x.endswith('ml') :
x = x[:-2]
x = x.strip().split()
x = " ".join(x[:-1])
if x.endswith('jar'):
x = x[:-3]
x = x.strip().split()
x = " ".join(x[:-1])
return x.strip()
y = d.map(filter_data_new)
df['name'] = y
df.to_csv('london_new'+str(time.time()).replace('.','_')+'.csv', index=False)
【问题讨论】:
-
你的意思是你有多个列名并且你想删除其中的某些?
-
@pygo 我正在处理一个名为 name 的特定列,它有 15,000 个产品标题。我想从产品名称中删除变体描述。例如:美丽香水 160z-cotton fresh-blue 。我只想说:美丽的香水
-
@pygo 的问题是它删除了一些 oz 而不是其他的,一些 ml 而不是其他的,我不知道为什么。或者只是从草莓中去除浆果,即使草莓是需要去除的东西列表中的名称
标签: python pandas data-cleaning fuzzy-logic fuzzywuzzy