Skip to content
Advertisement

Pandas: Replace value in column by using another column, if condition is true

I have the following dataframe:

df = pd.DataFrame({'ISIN': ['A1kT23', '4523', 'B333', '49O33'], 'Name': ['Example A', 'Name Xy', 'Example B', 'Test123'], 'Sector_x': ['test1', 'test2', 'test3', 'test4'],  'Sector_y': ['abc', '', '', 'xyz']})

I would like to replace value in column Sector_y by using column Sector_x, if Sector_y = ”

so that I get the following result:

df = pd.DataFrame({'ISIN': ['A1kT23', '4523', 'B333', '49O33'], 'Name': ['Example A', 'Name Xy', 'Example B', 'Test123'], 'Sector_x': ['test1', 'test2', 'test3', 'test4'],  'Sector_y': ['abc', 'test2', 'test3', 'xyz']})

I tried using the code

df['Sector_y'] = np.where('',['Sector_x'],['Sector_y'])

but didn’t deliver the result I wanted.

Any suggestions how to solve the problem?

Advertisement

Answer

Fix np.where

df['Sector_y'] = np.where(df['Sector_y'] =='', df['Sector_x'], df['Sector_y'])
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement