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?
CodePudding user response:
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.