【问题标题】:Pandas dataframe in python: Removing rows from df1 based on rows in df2python中的熊猫数据框:根据df2中的行从df1中删除行
【发布时间】:2018-03-02 21:46:33
【问题描述】:

我有两个数据框:

df1: contains all information
rowname a  b  c  d
R1      1  2  0  1
R2      2  2  0  1
R3      0  2  0  0
R4      1  2  0  1

df2: contains a subset of the rows and columns:
rowname a  b  c  
R1      1  2  0  
R2      2  2  0   
R4      1  2  0 

我想过滤掉所有不在df1 中的行df2。因此,对于这种情况,我希望在保留所有列的同时摆脱 df1 中的 R3。

我认为使用df1.merge(df2, ...) 可以实现这一点,但我尝试了各种参数,但均未成功。我正在使用python3。

【问题讨论】:

    标签: python python-3.x pandas dataframe merge


    【解决方案1】:

    Simpy 使用 isin() 过滤数据帧

    df1[df1.rowname.isin(df2.rowname)]
    
      rowname  a  b  c  d
    0      R1  1  2  0  1
    1      R2  2  2  0  1
    3      R4  1  2  0  1
    

    【讨论】:

      【解决方案2】:

      这是一种方式,仅匹配列['a', 'b', 'c']

      df = pd.concat([df1, df2])
      
      df = df.loc[df.duplicated(['a', 'b', 'c'], keep=False)]\
             .dropna(subset=['d'], axis=0)
      
      df['d'] = df['d'].astype(int)
      

      结果:

         a  b  c  d rowname
      0  1  2  0  1      R1
      1  2  2  0  1      R2
      3  1  2  0  1      R4
      

      【讨论】:

        猜你喜欢
        • 2015-12-17
        • 1970-01-01
        • 2020-09-20
        • 2021-04-26
        • 2017-10-04
        • 1970-01-01
        • 2019-05-01
        • 2016-09-05
        • 2015-11-07
        相关资源
        最近更新 更多