I have a dataframe like this
import pandas as pd
df = pd.DataFrame({'A':list('bbcddee'), 'B': list('klmnnoi')})
A B
0 b k
1 b l
2 c m
3 d n
4 d n
5 e o
6 e i
and I would like to create a dictionary from the columns A and B using e.g.
dict(zip(df.A, df.B))
Before doing this, I would like to check whether each value in A is mapped to only one value in B; if not, an error should be thrown; above that is not the case as b is mapped to k and l and e is mapped to o and i.
One way of approaching it would be:
df[df.groupby('A', sort=False)['B'].transform(lambda x: len(set(x))) > 1]
which returns
A B
0 b k
1 b l
5 e o
6 e i
However, that requires a lambda which might make it slow. Does anyone see an option to speed it up?
