Using where and between:

df['Age'] = df.Age.where(df.Age.between(5, 100))
df
   ID   Age
0   1   NaN
1   2   NaN
2   3  25.0
3   4   NaN
4   5  45.0

Another option using .loc:

df.loc[df.Age.between(5, 100), 'Age'] = np.nan
Answer from BENY on Stack Overflow
Discussions

python - Replace a row in Pandas DataFrame with 'NaN' based on condition - Stack Overflow
I have a Pandas DataFrame called df (378000, 82) and I would like to replace the entire row with NaN based on a specific condition. The condition is for any value in the column df.halon_gas that is... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Pandas: How to replace values to np.nan based on Condition for multiple columns - Stack Overflow
Here is my dataframe. I A B C D E F 1 9 4 0 T F F 2 0 5 1 S X J 3 1 8 0 G G J Here is my expected output. I want to replace if value in A ==0, repalce to np.nan in D. I A... More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 28, 2020
pandas - Python: how to replace NaN with conditions in a dataframe? - Stack Overflow
I have a dataframe df1 that corresponds to the egelist of nodes in a network and value of the nodes themself like the following: df node_i node_j value_i value_j 0 3 4 ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
September 7, 2018
python - Replace NaN with Condition based on another column - Stack Overflow
I have the following dataset with NaNs: County 0 City 0 State ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ i need to replace nan in one column with value for other col
r/learnpython on Reddit: I need to replace NaN in one column with value for other col
July 15, 2021 -

I've been working on learning Python and for something to code, I picked some VBA that I had.

In VBA:

     If Cells(I, "C").Value <> "" And Cells(I, "B").Value = "" Then
       Cells(I, "B").Value = Cells(I, "C").Value
     End If

It simply checks if colC is not Null and colB is Null, then replaces colB with the value from colC.

I can read in the csv file, I was able to select and delete some rows I didn't want, but I can't seem to get the syntax right for this...

Top answer
1 of 2
1

I understand from your question that you want to replace all the NaN values in Model with the Mode (Most Common Value) based on the values in Make. This can be done using the pandas library in Python. The code is as follows:

import pandas as pd

# Assuming you already have your dataset loaded into a DataFrame called 'df'

# Create a dictionary to store the mode for each 'Make'
make_mode_dict = {}

# Iterate through unique 'Make' values
for make in df['Make'].unique():
    # Filter the DataFrame to rows with the current 'Make' value and 'Model' not NaN
    make_subset = df.loc[(df['Make'] == make) & df['Model'].notna(), 'Model']
    
    # Find the mode of 'Model' for the current 'Make'
    mode_value = make_subset.mode().iloc[0]
    
    # Store the mode in the dictionary with 'Make' as the key
    make_mode_dict[make] = mode_value

# Function to replace NaN 'Model' values based on 'Make'
def replace_nan_model(row):
    if pd.isna(row['Model']):
        return make_mode_dict.get(row['Make'], None)
    return row['Model']

# Apply the function to fill NaN values in the 'Model' column
df['Model'] = df.apply(replace_nan_model, axis=1)

In the code above, we first create a dictionary make_mode_dict to store the mode of the Model column for each unique Make value. Then, we iterate through each unique Make value, filter the DataFrame to rows with that specific Make value and non-NaN Model values, find the mode of the Model column for that Make, and store it in the dictionary.

After that, we define a function replace_nan_model that takes a row from the DataFrame as input. If the Model value in the row is NaN, it looks up the mode from the make_mode_dict based on the corresponding Make value and returns the mode value. If the Model value is not NaN, it returns the original value.

Finally, we apply the replace_nan_model function to the DataFrame using the apply method along axis=1, which means we apply the function row-wise to fill in the NaN values in the Model column based on the Make value.

After running this code, the Model column will hopefully have NaN values replaced with the mode for each Make value in the DataFrame. Hope this helps!

2 of 2
0

I would say that the easiest way to do this is by masking out the nan values and then replacing from a dictionary.

import pandas as pd
import numpy as np

# Creating example dataset
df = pd.DataFrame({"brand": ["Audi", np.nan], "model": ["a4", "ELR"]})

# The dictionary with model to brand
model_to_brand = {"ELR": "CADILLAC", "E-TRON": "Audi"}

mask = df["brand"].isna() # Creating a boolean mask

# Only replacing values of the cars selected by the mask
df.loc[mask, "brand"] = df.loc[mask, "model"].replace(model_to_brand)

# Printing out the modified dataframe
print(df)

Hope this helps!

Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 58967949 โ€บ replace-nan-values-with-specific-value-per-column
python - Replace NaN values with specific value per column - Stack Overflow
If need replace missing values in all numeric columns use DataFrame.fillna by mean - it working because mean exclude non numeric columns: df = pd.DataFrame({ 'A':list('abcdef'), 'B':[4,np.nan,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,np.nan,1,0], 'E':[np.nan,3,6,np.nan,2,4], 'F':list('aaabbb') }) df1 = df.fillna(df.mean()) print (df1) A B C D E F 0 a 4.0 7 1.0 3.75 a 1 b 4.4 8 3.0 3.00 a 2 c 4.0 9 5.0 6.00 a 3 d 5.0 4 2.0 3.75 b 4 e 5.0 2 1.0 2.00 b 5 f 4.0 3 0.0 4.00 b
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.fillna.html
pandas.DataFrame.fillna โ€” pandas 3.0.5 documentation
Replace all NaN elements in column โ€˜Aโ€™, โ€˜Bโ€™, โ€˜Cโ€™, and โ€˜Dโ€™, with 0, 1, 2, and 3 respectively.
๐ŸŒ
Statology
statology.org โ€บ home โ€บ pandas: how to replace nan values with string
Pandas: How to Replace NaN Values with String
November 1, 2021 - #replace NaN values in all columns with empty string df.fillna('', inplace=True) #view updated DataFrame df team points assists rebounds 0 A 5.0 11.0 1 A 11.0 8.0 2 A 7.0 7.0 10.0 3 A 7.0 9.0 4 B 8.0 12.0 6.0 5 B 6.0 9.0 5.0 6 B 14.0 9.0 9.0 7 B 15.0 4.0
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.replace.html
pandas.DataFrame.replace โ€” pandas 3.0.5 documentation
Replace values based on boolean condition. ... Apply a function to a Dataframe elementwise. ... Map values of Series according to an input mapping or function. ... Simple string replacement. ... Regex substitution is performed under the hood with re.sub. The rules for substitution for re.sub are the same. Regular expressions will only substitute on strings, meaning you cannot provide, for example, a regular expression matching floating point numbers and expect the columns in your frame that have a numeric dtype to be matched.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-replace-values-in-column-based-on-condition-in-pandas
How to Replace Values in Column Based on Condition in Pandas? - GeeksforGeeks
November 15, 2024 - Code: Python3 # import pandas library ... can be easily performed using a single line DataFrame.fillna() and DataFrame.replace() method....