I have a dataframe like:
lst = [["High", "A"], ["High", "A"], ["High", "B"],["Medium", "A"], ["Medium", "B"], ["Medium", "C"]]
df = pd.DataFrame(lst, columns =["Class", "Grade"])
I need to get the mode (majority vote) of "Grade" in each "Class". If it's a tie vote, assign "x".
Below is what I expect to get:
| Class | Grade | Majority_vote |
|---|---|---|
| High | A | A |
| High | A | A |
| High | B | A |
| Medium | A | x |
| Medium | B | x |
| Medium | C | x |
This is my code:
df['majority_vote'] = df.groupby(['Class'])['Grade'].transform(lambda x: x.mode()[0])
I think the code will return 'nan' if it's a tie vote. Then, I will change 'nan' to 'x' later.
However, what I get is below:
| Class | Grade | Majority_vote |
|---|---|---|
| High | A | A |
| High | A | A |
| High | B | A |
| Medium | A | A |
| Medium | B | A |
| Medium | C | A |
At class "Medium", the code returns the 1st element ("A") instead of 'nan'.
Any other method is appreciated. Could you please help me? Thank you in advance.