2015-01-21 69 views
0

假設我有兩個數據幀A和B,每個數據幀都包含兩個稱爲x和y的列。 我想連接這兩個數據框,但不是在兩個數據框上的x和y列相等的行上,而是在A的x列是B的x列的子串並且y相同的行上。 例如Python在滿足條件的列上加入兩個數據幀

if A[x][1]='mpla' and B[x][1]='mplampla' 

我想要被捕獲。

上的SQL它會是這樣的:

select * 
from A 
join B 
on A.x<=B.x and A.y<=B.y. 

可以像這樣的蟒蛇做什麼?與那就是你必須遍歷的A所有元素

import numpy.core.defchararray as ca 

ca.find(B.x.values.astype(str), 'mpla') >= 0 

問題:

+0

您提供的SQL沒有實現您描述的內容。你想要哪一個:子串匹配還是字典比較? – 2015-01-21 05:57:34

+0

哦,我知道,這只是一個例子。在這個特定的場合,我需要子串匹配。但我理想的情況是我想了解是否有辦法爲其他關係實現它(例如,如果我有數字等...) – yortos 2015-01-21 06:08:18

+0

這裏是一個類似的問題... http://stackoverflow.com/questions/22723286/complex-joins-in-pandas – DataByDavid 2015-01-22 03:27:40

回答

0

您可以對所有的字符串時在一列匹配一個字符串,像這樣。但如果你能負擔得起,它應該工作。

參見:pandas + dataframe - select by partial string

+0

謝謝,我會給這個鏡頭,但他們都是非常大的文件,這就是爲什麼我正在尋找一個更有效的方式。 – yortos 2015-01-21 06:11:44

+0

如果你在標準包中找不到任何東西,你應該考慮編寫你自己的C擴展。然後你可以實現你能想到的任何有效的算法。 – 2015-01-21 06:13:09

0

你可以嘗試像

B.x.where(B.x.str.contains(A.x), B.index,   axis=index) #this would give you the ones that don't match 


B.x.where(B.x.str.match(A.x, as_indexer=True), B.index, axis=index) #this would also give you the one's that don't match. You could see if you can use the "^" operator used for regex to get the ones that match. 

你也可以也許嘗試

np.where(B.x.str.contains(A.x), B.index, np.nan) 

,你也可以試試:

matchingmask = B[B.x.str.contains(A.x)] 

matchingframe = B.ix[matchingmask.index] #or 

matchingcolumn = B.ix[matchingmask.index].x #or 

matchingindex = B.ix[matchingmask.index].index 

所有這些假設你有兩個幀相同的索引(我認爲)

你想看看字符串方法:http://pandas.pydata.org/pandas-docs/stable/text.html#text-string-methods

要在正則表達式和熊貓閱讀了其中的方法:http://pandas.pydata.org/pandas-docs/dev/indexing.html#the-where-method-and-masking