【发布时间】:2021-11-20 00:26:42
【问题描述】:
我需要在我的 df 的两列 -A 和 B- 上执行以下步骤,并将结果输出到 C:
1) check if value from B is present in A -on row, at any position
2) if present but in another format then remove
3) add value from B in A and output in C
A B C
tshirt for women TSHIRT TSHIRT for women
Zaino Estensibile SJ Gang SJ Gang Zaino Estensibile
Air Optix plus AIR OPTIX AIR OPTIX plus
在 A 和 B 之间连接并删除重复项的解决方法:
版本 1
def uniqueList(row):
words = str(row).split(" ")
unique = words[0]
for w in words:
if w.lower() not in unique.lower() :
if w.lower()not in my_list:
unique = unique + " " + w
return unique
df["C"] = df["C"].apply(uniqueList)
版本2
sentences = df["B"] .to_list()
for s in sentences:
s_split = s.split(' ') # keep original sentence split by ' '
s_split_without_comma = [i.strip(',') for i in s_split]
# method 1: re
compare_words = re.split(' |-', s)
# method 2: itertools
compare_words = list(itertools.chain.from_iterable([i.split('-') for i in s_split]))
method 3: DIY
compare_words = []
for i in s_split:
compare_words += i.split('-')
# strip ','
compare_words_without_comma = [i.strip(',') for i in compare_words]
start to compare
need_removed_index = []
for word in compare_words_without_comma:
matched_indexes = []
for idx, w in enumerate(s_split_without_comma):
if word.lower() in w.lower().split('-'):
matched_indexes.append(idx)
if len(matched_indexes) > 1: # has_duplicates
need_removed_index += matched_indexes[1:]
need_removed_index = list(set(need_removed_index))
# keep remain and join with ' '
print(" ".join([i for idx, i in enumerate(s_split) if idx not in need_removed_index]))
# print(sentences)
print(sentences)
这些都不能正常工作,因为这不是最好的方法。
【问题讨论】:
-
您的问题是什么?您如何编辑问题并添加您尝试过的所有内容以及您在这里遇到的问题。
-
这似乎是一道家庭作业题,你自己的努力在哪里?
-
@Umar.HI 实际上已经尝试了一种解决方法,连接和删除重复的有效但在某些情况下不需要删除所有重复的单词,整数和其他特定单词也是如此。
-
你能把代码也贴出来吗?
-
@Umar.H 当然,完成。还有第三个尝试,但我无法在问题中发布更多代码
标签: python pandas duplicates concatenation