Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Grouping of subset of a Column in pandas

Having a data set as below.Here I need to group the subset in column and fill the missing values using mode method.

Need to group the value ‘Tom’ from name and fill the missing value in value using mode.

     Name  Value
0     Tom   20.0
1     Tom   20.0
2     Tom    NaN
3    nick   19.0
4    nick   18.0
5   krish   15.0
6    nick   15.0
7    nick   20.0
8    jack    NaN
9     Tom   23.0
10    Tom    NaN

I tried the code below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data['value']= data.loc[data["Name"]=='Tom'].fillna(data['value'].mode()[0], inplace=True)

Didn’t get the output as expected.

>Solution :

To replace on specific conditions you could use np.where() to evaluate the condition, when it is met, replace it with the mode, otherwise retain the column’s original value. Kindly try:

data['Value'] = np.where(data['Name'] =='Tom',data['Value'].fillna(data['Value'].mode()[0]),data['Value'])

This returns:

     Name  Value
0     Tom   20.0
1     Tom   20.0
2     Tom   20.0
3    nick   19.0
4    nick   18.0
5   krish   15.0
6    nick   15.0
7    nick   20.0
8    jack    NaN
9     Tom   23.0
10    Tom   20.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading