簡體   English   中英

大熊貓合並返回的行多於任一數據框包含的行

[英]pandas merge returning more rows than either dataframe contains

我正在嘗試合並兩個數據幀,其中結果數據幀只是列1-8相同的重復行。 這些是我的數據框:

check_df  0   1   2     3          4      5           6            7       8        
     0    1  794  1  192.168.0.1  qrf   default    SQL Server  Windows  cilaric98
     1    2  2558 1  192.168.0.2  qrf   default    Oracle      Windows  cilaric98
     2    3  2840 1  192.168.0.3  qrf   default    Oracle      Windows  cilaric008
     3    4  3290 1  192.168.0.4  qrf   default    SQL Server  Windows  cilaric98
     4    5  3175 1  192.168.0.5  a2d2  default    SQL Server  Windows  cilaric98
     5    6  4189 1  192.168.0.21 a2d2  default    SQL Server  Windows  cilaric98 

dataframe  0   1   2     3          4      5           6            7       8        
     0    1.0 794  1  192.168.0.1  qrf   default    SQL Server  Windows  cilaric98
     1    2.0 2558 1  192.168.0.2  qrf   default    Oracle      Windows  cilaric98
     2    3.0 2840 1  192.168.0.3  qrf   default    Oracle      Windows  cilaric008
     3    4.0 3290 1  192.168.0.4  qrf   default    SQL Server  Windows  cilaric98
     4    5.0 3175 1  192.168.0.5  a2d2  default    SQL Server  Windows  cilaric98 
     5    6.0 3915 1  192.168.0.6  a2d2  default    SQL Server  Windows  cilaric98 
     6    7.0 3886 1  192.168.0.7  a2d2  default    SQL Server  Windows  cilaric98 

運行此:

dupes_df = check_df.merge(dataframe, how='inner', on=[1,2,3,4,5,6,7], indicator=True).drop_duplicates(keep='first')
dupes_df = dupes_df[dupes_df['_merge'] == 'both']

返回幾乎兩倍的列和更多的行,然后返回其中一個數據框。 我期望的輸出是:

    check_df  0   1   2     3          4      5           6            7       8        
         0    1  794  1  192.168.0.1  qrf   default    SQL Server  Windows  cilaric98
         1    2  2558 1  192.168.0.2  qrf   default    Oracle      Windows  cilaric98
         2    3  2840 1  192.168.0.3  qrf   default    Oracle      Windows  cilaric008
         3    4  3290 1  192.168.0.4  qrf   default    SQL Server  Windows  cilaric98
         4    5  3175 1  192.168.0.5  a2d2  default    SQL Server  Windows  cilaric98

您可以嘗試以下方法:

check_df.merge(dataframe, on=[1,2,3,4,5,6,7], suffixes=('','_y'))[check_df.columns]

輸出:

   0       1            2            3        4           5           6  \
0  1     794            1  192.168.0.1      qrf     default  SQL Server   
1  2  2558 1  192.168.0.2          qrf  default      Oracle     Windows   
2  3  2840 1  192.168.0.3          qrf  default      Oracle     Windows   
3  4  3290 1  192.168.0.4          qrf  default  SQL Server     Windows   
4  5  3175 1  192.168.0.5         a2d2  default  SQL Server     Windows   

            7          8  
0     Windows  cilaric98  
1   cilaric98       None  
2  cilaric008       None  
3   cilaric98       None  
4   cilaric98       None  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM