【问题标题】:Python Pandas: How to use 'where' and 'isin' with two conditions?Python Pandas:如何在两个条件下使用“where”和“isin”?
【发布时间】:2015-07-02 18:57:48
【问题描述】:

我有一个数据框“dfm”:

      match_x            org_o           group   match_y
0       012  012 Smile Communications     92      012
1       012                 012 Smile     92      000
2   10types                   10TYPES     93      10types
3   10types               10types.com     97      10types
4  360works                  360WORKS     94      360works
5  360works              360works.com     94      360works

我想要一个名为'tag'的'a'列。对于 dfm 中的每个组织,当 match_x 和 match_y 相等并且它们有一个唯一组时,标签将为“TP”,否则为“FN”。这是我使用的代码:

a['tag'] = np.where(((a['match_x'] == a['match_y']) & (a.groupby(['group', 'match_x','match_y'])['group'].count() == 1)),'TP', 'FN')

但我收到此错误:

TypeError: 'DataFrameGroupBy' object is not callable

有人知道怎么做吗?

【问题讨论】:

    标签: python pandas group-by conditional-statements


    【解决方案1】:

    让我们稍微分解一下你的大声明:

    a['tag'] = np.where(((a['match_x'] == a['match_y']) & (a.groupby(['group', 'match_x','match_y'])['group'].count() == 1)),'TP', 'FN')
    

    揭开面具:

    mask = ((a['match_x'] == a['match_y']) & (a.groupby(['group', 'match_x','match_y'])['group'].count() == 1))
    a['tag'] = np.where(mask,'TP', 'FN')
    

    打破面具:

    mask_x_y_equal = a['match_x'] == a['match_y']
    single_line = a.groupby(['group', 'match_x','match_y']).size() == 1
    mask = (mask_x_y_equal & single_line)
    a['tag'] = np.where(mask,'TP', 'FN')
    

    如果你这样做,错误会更明显。 single_line 掩码的长度与 mask_x_y_equal 的长度不同。 这成为一个问题,因为 & 符号不关心系列的索引,这意味着您当前在这里有一个静默错误。

    我们可以通过在数据框内操作来消除这个静默错误:

    df_grouped = a.groupby(['group', 'match_x','match_y']).size() # size does what you do with the ['group'].count(), but a bit more clean.
    df_grouped.reset_index(inplace=True) # This makes df_grouped into a dataframe by putting the index back into it.
    df_grouped['equal'] = df_grouped['match_x'] == df_grouped['match_y'] # The mask will now be a part of the dataframe
    
    mask = (df_grouped['equal'] & (df_grouped['0'] == 1)) # Now we create your composite mask with comparable indicies
    a['tag'] = np.where(mask, 'TP', 'FN')
    

    这可能会也可能不会解决您的“TypeError: 'DataFrameGroupBy' object is not callable”。无论哪种方式,将您的语句分解为多行都会向您显示更多错误可能是什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2022-01-22
      • 2020-01-05
      • 2016-10-19
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多