我试图在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 ?
编辑示例数据:
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