2017-08-10 55 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