How do I replace every NaN value in every column by minimum value of that column in pandas?

Question:

I have a dataframe and I want to replace every NaN value in every column by min() of the column, how do I do that?enter image description here

Asked By: Glaurung

||

Answers:

To replace all NaN values in a dataframe with the minimum value of the respective column, you can use the pandas DataFrame.fillna() method in combination with the DataFrame.min() method.

For example, suppose you have a dataframe df with the following values:

      col1  col2
0     NaN     1
1     NaN     3
2     5.0     2
3     6.0     NaN
4     NaN     4

To replace all NaN values with the minimum value of each column, you can use the following code:

df.fillna(df.min())

This will return a new dataframe with the NaN values replaced by the minimum value of each column:

      col1  col2
0     5.0     1
1     5.0     3
2     5.0     2
3     6.0     1
4     5.0     4

Note that the fillna() method will only replace NaN values in the original dataframe. If you want to save the changes to the original dataframe, you can use the inplace parameter like this:

df.fillna(df.min(), inplace=True)

This will replace the NaN values in the original dataframe df and return None.

Answered By: Cyzanfar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.