[英]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
我想在“ a”列中添加一个名为“ tag”的标签。 对于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'对象不可调用”。 无论哪种方式,将您的语句分成多行都会向您显示更多错误信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.