I need a pandas code for the following data.Here I need a condition for replace the value.if product name is A,price needs to be the mode value of A and replace all the value.At the end The value of A is 5 in every row.
Product | Price |
---|---|
A | 5 |
A | 6 |
A | 7 |
B | 8 |
B | 8 |
B | 4 |
A | 5 |
A | 5 |
A | 5 |
A | Nan |
c | 4 |
D | 3 |
CodePudding user response:
You could create a dictionary, keys
being the values from Product column and values
will be their respective mode
price, and then map
it back to your dataframe based on your Product column:
df.assign(Price=df['Product'].map(
df.groupby(['Product'])['Price'].agg(pd.Series.mode).to_dict()))
prints:
Product Price
0 A 5
1 A 5
2 A 5
3 B 8
4 B 8
5 B 8
6 A 5
7 A 5
8 A 5
9 c 4
10 D 3