Home > Net >  How to get the second smallest value in pandas series (pandas.Series.min)?
How to get the second smallest value in pandas series (pandas.Series.min)?

Time:01-24

Some of my data contains "0.0" as a placeholder for empty values.

I need to grab the smallest value that's not "0.0".

It would be easy in excel since it will ask you which smallest value you want, but it doesn't look like pandas.Series.min has the option to choose the second smallest.

Keep in mind, I will sometimes have more than one "0" value.

How can I get the smallest value that's not a 0.0?

CodePudding user response:

If you have a series s, then you can try:

s = pd.Series([1,0.0,2,3])
min(s[s != 0.0])

This will return 1.0 in this example. This should give you the second smallest value assuming that all values in your series are greater than or equal to 0

CodePudding user response:

Use:

s.where(lambda x: x > 0).min()

if it can be negative:

s.where(lambda x: x != 0).min()

CodePudding user response:

I assume you have only positive numbers? If so, here's an alternative solution, sort and take the second value

df.sort_values(by='column_name')['column_name'].values[1]

CodePudding user response:

So many different ways: :)

min([ x for x in df['Values'] if x != 0.0])
  •  Tags:  
  • Related