【问题标题】:Compare two columns ( string formats) in two data frames while length of columns is not the same比较两个数据框中的两列(字符串格式),而列的长度不同
【发布时间】:2017-05-12 15:54:22
【问题描述】:

以下是两个数据框: 数据框A:

index  codes     
1        A      
2        B    
3        C
4        D

数据框 B

index    cym
1         A
2         L
3         F
4         B
5         N
6         X

A 和 B 的长度不相等。我想将“codes”列(数据框A)与“cym”列(数据框B)进行比较,并返回这两列之间的差异加上数据框B的索引列中的数据。输出是这样的:

index    cym
2        L
3        F
5        N
6        X

我尝试使用合并和等于函数来解决它。但我无法生成输出。

【问题讨论】:

  • 我检查你的最后一个问题,如果有 3 个连续的 NaN 怎么办?或者样本中只有 2 个或 1 个 NaN,而不是 3,4 个或更多连续的 NaN?谢谢。

标签: python pandas dataframe compare


【解决方案1】:

你可以使用isin:

B[~B.cym.isin(A.codes)]

#index  cym
#1   2    L
#2   3    F
#4   5    N
#5   6    X

【讨论】:

    【解决方案2】:

    @Psidom 答案的更详细但更快的版本。

    mask = ~np.in1d(B.cym.values, A.codes.values)
    pd.DataFrame(
        B.values[mask],
        B.index[mask],
        B.columns
    )
    
      index cym
    1     2   L
    2     3   F
    4     5   N
    5     6   X
    

    时机

    %timeit B[~B.cym.isin(A.codes)]
    1000 loops, best of 3: 348 µs per loop
    
    %%timeit
    mask = ~np.in1d(B.cym.values, A.codes.values)
    pd.DataFrame(
        B.values[mask],
        B.index[mask],
        B.columns
    )
    10000 loops, best of 3: 194 µs per loop
    

    【讨论】:

      【解决方案3】:

      为了完整起见:

      In [22]: B.query("cym not in @A.codes")
      Out[22]:
         index cym
      0      2   L
      1      3   F
      2      5   N
      3      6   X
      

      【讨论】:

        猜你喜欢
        • 2017-02-07
        • 1970-01-01
        • 2021-02-25
        • 1970-01-01
        • 2017-12-24
        • 2018-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多