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

Time:02-02

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))

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

CodePudding user response:

(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
  • Related