26

Since one column of my pandas dataframe has nan value, so when I want to get the max value of that column, it just return error.

>>> df.iloc[:, 1].max()
'error:512'

How can I skip that nan value and get the max value of that column?

3
  • 3
    Please post the DataFrame. The max function skips nan by default - see docs. Commented Jul 21, 2016 at 15:33
  • 1
    What is "error 512"? Is that something written by you? python/pandas does not throw that error AFAIK. Commented Jul 21, 2016 at 16:20
  • @Merlin, 'error:512' is returned by the python console. Commented Jul 22, 2016 at 2:03

6 Answers 6

23

You can use NumPy's help with np.nanmax, np.nanmin :

In [28]: df
Out[28]: 
   A   B  C
0  7 NaN  8
1  3   3  5
2  8   1  7
3  3   0  3
4  8   2  7

In [29]: np.nanmax(df.iloc[:, 1].values)
Out[29]: 3.0

In [30]: np.nanmin(df.iloc[:, 1].values)
Out[30]: 0.0
Sign up to request clarification or add additional context in comments.

Comments

18

You can use Series.dropna.

res = df.iloc[:, 1].dropna().max()

1 Comment

This is quite nice. np.nanmin and np.nanmax are sensitive to warnings as discussed here, but this approach solves that issue.
4

if you dont use iloc or loc, it is simple as:

df['column'].max()

or

df['column'][df.index.min():df.index.max()]

or any kind of range in this second square brackets

Comments

4

You can set numeric_only = True when calling max:

df.iloc[:, 1].max(numeric_only = True)

Attention:

For everyone trying to use it with pandas.series This is not working nevertheless it is mentioned in the docs

See post on github

Comments

2

Dataframe aggregate function.agg() will automatically ignore NaN value. df.agg({'income':'max'})

Besides, it can also be use together with .groupby

df.groupby('column').agg({'income':['max','mean']})

Comments

1

When the df contains NaN values it reports NaN values, Using np.nanmax(df.values) gave the desired answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.