使用具有70个唯一值的分类组将第一个False值转换为True



我试图在Pandas Dataframe的列中将第一次出现的False转换为True。所讨论的列包含True、False和null值。我现在的代码是:

df.loc[df.groupby('categorical_col')[''].idxmin(), 'target_col'] = True

然而这给了我以下错误:

TypeError: reduction operation 'argmin' not allowed for this dtype

在合并分类组时,如何将第一次出现的False转换为True ?

编辑示例数据:

tbody> <<tr>BBBBB
categorical_col target_col

问题是列target_col不是布尔值,而是由字符串填充:

print (df)
categorical_col  target_col
0                1       False
1                1       False
2                2        True
print (df.target_col.dtypes)
object

对字符串'True'进行布尔比较:

df['target_col'] = df['target_col'].eq('True')
df.loc[df.groupby('categorical_col')['target_col'].idxmin(), 'target_col'] = True
print (df)
categorical_col  target_col
0                1        True
1                1       False
2                2        True

相关内容

最新更新