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

Create a new column by extracting the smallest tuple from a data frame column

I have a dataframe with a column that contains tuples. I would like to create a new column that extracts the smallest tuple from the tuple column.

What I have tried so far

mydataframe['min_values'] = mydataframe['tuple_column'].apply(lambda x: min(x))

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

This above approach seems to work when I have at least 2 tuples, but it fails when I only have one tuple e.g. 5 in the example below. Could you guys please suggest a method that would help me accomplish this task in a better manner?

Example and desired result

Tuple Column New Column
(1,2,3,5) 1
(10,11) 10
(5) 5

Thanks

>Solution :

(5) is not a tuple, this is 5. Use numpy.min that handles scalar values as input:

import numpy as np
df['New Column'] = df['Tuple Column'].apply(np.min)

Output:

   Tuple Column  New Column
0  (1, 2, 3, 5)           1
1      (10, 11)          10
2             5           5
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