Python Pandas: 'where' 和 'isin' 两个条件如何使用?

Python Pandas: How to use 'where' and 'isin' with two conditions?

我有一个数据框 '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

有人知道怎么做吗?

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

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"。无论哪种方式,将您的语句分解成多行都会向您显示更多可能的错误。