2016-02-11 21 views
0

我有兩列數據:的Excel(或Python/R/SQL):將所有匹配在不同的行

A B 
Dog Cat 
Cat Car 
Car Pie 
Car Cat 
Cat Pie 

我想什麼是創建一個第三塔,該第二列值相匹配在第一列中出現該值,並抓取隨後的第二列值以放入我們正在查看的原始行的第三列。很抱歉的混亂一段裏面,它應該看起來是這樣的:

A B C 
Dog Cat Car 
Dog Cat Pie 
Cat Car Pie 
Cat Car Cat 
Car Pie 
Car Cat Car 
Car Cat Pie 
Cat Pie 

這是因爲它通過,並在第一行會看到「貓」是第二列的值,尋找所有比賽在第一列(其中有兩個)和他們隨後的第二列值(汽車和派)。然後創建一行,其中每個後續值顯示在第三列中。 「Car Pie」或「Cat Pie」沒有第三列值,因爲沒有行以「Pie」開頭,所以沒有任何匹配。

希望這是有道理的!如果Excel不是這方面的正確工具,我也會對其他建議感興趣,但我知道一些Python,R和SQL。

+0

這些是我們希望OP可以提供更接近實際數據的數據樣本的問題之一,因爲這太抽象了。可能會得到更好的迴應。 – Parfait

回答

0

我找到了一種方法R中做到這一點:

TwoSteps <- [import dataframe here] 

#Create an empty dataframe to hold all three-step transitions 
ThreeSteps <- data.frame(First = character(), 
       Second=character(), 
       Third=character(), 
       stringsAsFactors=FALSE) 

#Loop through all rows in TwoSteps. For each row, 
#check all values in column 1 for matches. When a match is found, 
#Add first and second from the original row to ThreeSteps First and Second, then 
#Add second from matched row to Third 

N = nrow(TwoSteps) 
row = 1 

for (i in 1:N) { 
for (g in 1:N){ 
    if(TwoSteps[i,2]==TwoSteps[g, 1]){ 
    ThreeSteps[row, 1] = TwoSteps[i, 1] 
    ThreeSteps[row, 2] = TwoSteps[i, 2] 
    ThreeSteps[row, 3] = TwoSteps[g, 2] 
    row = row + 1 
    } 
} 
} 
0

這也可以在SQL使用左手來完成加入與同桌:

Create Table #Example (A varchar(3), B varchar(3)); 

INSERT INTO #Example (A, B) 
    values ('Dog', 'Cat'), 
    ('Cat', 'Car'), 
    ('Car', 'Pie'), 
    ('Car', 'Cat'), 
    ('Cat', 'Pie'); 

Select t1.*, t2.B as C 
    from #Example t1 
    left JOIN #Example t2 on t1.B=t2.A 

的結果是:

A B B1 
Dog Cat Car 
Dog Cat Pie 
Cat Car Pie 
Cat Car Cat 
Car Pie (null) 
Car Cat Car 
Car Cat Pie 
Cat Pie (null)