Home > Blockchain >  how to fill nan value based on another column
how to fill nan value based on another column

Time:12-24

i have to filter value column_A 1st and then Fill the nan value as team 1 for abc and team 2 for def

Column_A Column_B
abc team 1
def team 5
def team 5
def NaN
abc team 1
abc NaN

CodePudding user response:

IIUC, try this using fillna:

df['Column_B'] = df['Column_B'].fillna(df['Column_A'].map({'abc':'team 1', 'def' : 'team 2'}))
df

Output:

  Column_A Column_B
0      abc   team 1
1      def   team 5
2      def   team 5
3      def   team 2
4      abc   team 1
5      abc   team 1

CodePudding user response:

You can set index to your reference column and use a dictionary:

df['Column_B'] = df.set_index('Column_A')['Column_B']\
.fillna({'abc':'team 1', 'def' : 'team 2'}).values
  • Related