Skip to content Skip to sidebar Skip to footer

How To Replace Certain Rows By Shared Column Values In Pandas Dataframe?

Let's say I have the following pandas DataFrame: import pandas as pd data = [['Alex',10],['Bob',12],['Clarke',13], ['Bob', '#'], ['Bob', '#'], ['Bob', '#']] df = pd.DataFrame(dat

Solution 1:

try this,

d= df[df['Age']!='#'].set_index('Name')['Age']
df['Age']=df['Name'].replace(d)

O/P:

     Name Age
0    Alex  10
1     Bob  12
2  Clarke  13
3     Bob  12
4     Bob  12
5     Bob  12
6  Clarke  13

Solution 2:

You want to use the valid values to fill the invalid ones? In that case, use map:

v = df.assign(Age=pd.to_numeric(df['Age'], errors='coerce')).dropna()
df['Age'] = df['Name'].map(v.set_index('Name').Age)  

df
     Name   Age
0    Alex  10.0
1     Bob  12.0
2  Clarke  13.0
3     Bob  12.0
4     Bob  12.0
5     Bob  12.0
6  Clarke  13.0

Post a Comment for "How To Replace Certain Rows By Shared Column Values In Pandas Dataframe?"