I have some data stored in df1:
| id1 | id2 | product |
|-----|----------|---------|
| 1 | abc-2323 | Upload |
| 1 | 234234 | Upload |
| 1 | 43322 | Upload |
| 2 | abc-449 | Upload |
| 3 | abc-495 | Upload |
| 3 | 432 | Upload |
| 3 | 6543 | Upload |
Per id1 and product, I want to count the distinct id2s based on weather they begin with abc- or not. I have tried a conditional aggregation like this:
agg_data = (
df1
.groupby('id1', 'product')
.agg(
sf.when(~ sf.col('id2').like('abc-%'), sf.countDistinct('id2')).alias('id2_count_without_abc'),
sf.when(sf.col('id2').like('abc-%'), sf.countDistinct('id2')).alias('is2_count_with_abc')
)
)
However this errors out that id2 is neither present in the group by, nor is it an aggregate function. I'm unsure why I cannot do this conditional since simply sf.countDistinct('id2') would work by itself. E.g. No problem with this:
agg_data = (
df1
.groupby('id1', 'product')
.agg(
sf.countDistinct('id2').alias('id2_count_without_abc'),
sf.countDistinct('id2').alias('is2_count_with_abc')
)
)