2017-08-10 77 views
0

有谁知道是否有可能用像apply函数更快的东西替换Python中的双循环? 例如,我有这样的数据帧:替换双循环Python与应用

df = pd.DataFrame() 
df["col_1"] = ["hello", "salut","hello", "bye", "bye","hi","hello", "hello"] 
df["col_2"] = ["dog", "dog", "dog", "cat", "cat", "mouse","dog","cat"] 
df["col_3"] = [100,45,100,51,51,32,100,85] 

和此功能:

def f (l1, l2): if list(l1) == list(l2) : return 1 else: return 0

它返回1,如果2列表是相同的,否则为0。我想应用这个函数来创建一个“类似”这样的列:enter image description here

我可以很容易地做一个双循环,但我想这样做更快,复杂性较低。

谢谢你的帮助! :)

回答

1

基本上你想找到具有重复项的色组合,并将它们标记为1列“相似”。 pandas.DataFrame.duplicated正是这么做的,你只需要做:

df.duplicated(keep=False) 

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html#pandas.DataFrame.duplicatedkeep=False将标记所有的复印件,True

然后你只需要转换布尔为int:

df['similar'] = list(map(int, df.duplicated(keep=False))) 
+0

由于是快10倍! – Bennox75