我需要清理一个数据帧,删除重复的信息。例如:
name strength
770 Vitamin B12 Tab 500mcg 500 mcg
771 Vitamin B12 Tab 5mcg 5 mcg
772 Vitamin B12 Tablets 250mcg 250 mcg
773 Vitamin B12-folic Acid None
774 Vitamin B6 & B12 With Folic Acid None
775 Vitamin Deficiency Injectable System - B12 None
776 Vitamine 110 Liq None
777 Vitamine B-12 Tab 100mcg 100 mcg
778 Vitamine B12 25 Mcg - Tablet 25 mcg
779 Vitamine B12 250mcg 250 mcg
从第一name
列中,我需要删除strength
中的信息,即:
name strength
770 Vitamin B12 Tab 500 mcg
771 Vitamin B12 Tab 5 mcg
772 Vitamin B12 Tablets 250 mcg
773 Vitamin B12-folic Acid None
774 Vitamin B6 & B12 With Folic Acid None
775 Vitamin Deficiency Injectable System - B12 None
776 Vitamine 110 Liq None
777 Vitamine B-12 Tab 100 mcg
778 Vitamine B12 - Tablet 25 mcg
779 Vitamine B12 250 mcg
注意,name
中的强度表示可能与strength
列中的强度表示不完全对应,直到空格(500 mcg对500 mcg)
我的简单解决方案是循环所有可能的strength
组合,如果name
列中有匹配项,则替换为空字符:
new_df = []
for i in df:
for j in df.strength.dropna().drop_duplicates().tolist():
for k in i.split():
if j == k:
new_df.append((i, i.replace(j, '')))
print(new_df)
它确实有效,但是,我有大量的数据,这是最不符合pythonic和最不高效的实现方式。你知道吗
有什么建议吗?你知道吗
我可能无法与所有可能的力量组合相匹配。由于两个列的项目似乎包含大致相同的字符,所以使用strength列来模糊搜索name列就足够了。你知道吗
你可以搜索不区分大小写的有和没有空格,你可能会得到大多数项目完成。你知道吗
不区分大小写的搜索可以通过python中的正则表达式完成:
当然,用变量替换文本。你知道吗
编辑:可能有一种更有效的方法来处理正则表达式,所以如果有人更精通正则表达式,我很乐意学习。你知道吗
这可能是一个更好的方法。首先,我们正在减少数据和for循环之一,这将使代码的复杂性由o(n3)变为o(n2)
使用
re
包删除不需要的冗余字符串,并使用apply
函数删除pandasDataFrame
中的行。你知道吗在下面的代码中,您可以看到一个可能的解决方案:
然后输出
DataFrame
:这样,您就可以使用
strength
列在name
列中查找冗余字符串并将其删除,同时考虑到冗余字符串之间可能没有空格。你知道吗相关问题 更多 >
编程相关推荐