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

How to calculate mean value of values on column which go comma?

I have a dataframe:

id   value
a1   1,2
b2   4
c1   NaN
c5   9,10,11

I want to create a new column mean_value which is equal to mean values in column value:

id   value     mean_value
a1   1,2          1.5
b2   4            4
c5   9,10,11      10

and I also want to remove those values in NaN in it. How to do that?

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

>Solution :

Here’s one way using str.split and mean:

df = df.assign(mean_value=df['value'].str.split(',', expand=True).astype(float)
               .mean(axis=1)).dropna()

Output:

   id    value  mean_value
0  a1      1,2         1.5
1  b2        4         4.0
3  c5  9,10,11        10.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