2016-07-07 3 views
3

다른 길이의 팬더 데이터 프레임을 두 개 비교하고 일치하는 인덱스 번호를 식별하고 싶습니다. 값이 일치하면 새 열의 값에 플래그를 지정하고 싶습니다. 이러한 정말 색인 경우새 열의 데이터 프레임 간 플래그 유사도

df1: 
Index Column 1 
41660 Apple 
41935 Banana 
42100 Strawberry 
42599 Pineapple 

df2: 
Index Column 1 
42599 Pineapple 

Output: 
Index Column 1 'Matching Index?' 
41660 Apple 
41935 Banana 
42100 Strawberry 
42599 Pineapple True 
+0

가능한 중복 [ 두 개의 Python Pandas 데이터 프레임의 두 열을 비교하고 공통 행을 얻는 방법] (http://stackoverflow.com/questions/30291032/comparing-2-columns-of-two-python-pandas-dataframes-and-getting-the-common -rows) – Andy

답변

4

당신은 인덱스에 intersection를 사용할 수 있습니다

In [61]: 
df1.loc[df1.index.intersection(df2.index), 'flag'] = True 
df1 

Out[61]: 
     Column 1 flag 
Index     
41660  Apple NaN 
41935  Banana NaN 
42100 Strawberry NaN 
42599 Pineapple True 

그렇지 않으면 isin를 사용

In [63]: 
df1.loc[df1['Index'].isin(df2['Index']), 'flag'] = True 
df1 

Out[63]: 
    Index Column 1 flag 
0 41660  Apple NaN 
1 41935  Banana NaN 
2 42100 Strawberry NaN 
3 42599 Pineapple True 
+1

감사합니다.이게 내 문제를 해결했습니다. – zbug

2

+1 @ EdChum의 대답에. 당신이 일치하는 열의 True 아닌 다른 값으로 살 수있는 경우 시도 :

>>> df1.merge(df2,how='outer',indicator='Flag') 
    Index  Column  Flag 
0 41660  Apple left_only 
1 41935  Banana left_only 
2 42100 Strawberry left_only 
3 42599 Pineapple  both 
2

가 ISIN를 사용하여() - 방법 :

import pandas as pd 

df1 = pd.DataFrame(data=[ 
    [41660, 'Apple'], 
    [41935, 'Banana'], 
    [42100, 'Strawberry'], 
    [42599, 'Pineapple'], 
         ] 
        , columns=['Index', 'Column 1']) 

df2 = pd.DataFrame(data=[ 
    [42599, 'Pineapple'], 
         ] 
        , columns=['Index', 'Column 1']) 

df1['Matching'] = df1['Index'].isin(df2['Index']) 
print(df1) 

출력 :의

Index Column 1 Matching 
0 41660  Apple False 
1 41935  Banana False 
2 42100 Strawberry False 
3 42599 Pineapple  True 
+1

'isin'은 이미 내 대답에 언급되어있다. – EdChum

관련 문제