ARJ
ARJ

Reputation: 2080

How to add prefix to rows of a columns if (conditions met)

I have a data frame with certain columns and rows and in which I need to add prefix to rows from one of the columns if it meet certain condition,

df = pd.DataFrame({'col':['a',0,2,3,5],'col2':['PFD_1','PFD_2','PFD_3','PFD_4','PFD_5']})
Samples=pd.DataFrame({'Sam':['PFD_1','PFD_5']})

And I need to add a suffix to df.col2 based on values in Samples dataframe, and I tried it with np.where as following,

df['col2'] = np.where(df.col2.isin(samples.Sam),'Yes' + df.col2, 'Non_'+ df.col2)

Whhich throws error as,

TypeError: can only perform ops with scalar values

It doesn't return what I am asking for, and throwing errors in the end the data frame should look like,

>>>df.head()

col col2
a   Yes_PFD_1
0   no_PFD_2
2   no_PFD_3
3   no_PFD_4
5   Yes_PFD_5

Upvotes: 0

Views: 4880

Answers (1)

ashishsingal
ashishsingal

Reputation: 2978

Your code worked fine for me once I changed the capitalization of 'samples' ..

import pandas as pd
import numpy as np
df = pd.DataFrame({'col':['a',0,2,3,5],'col2': ['PFD_1','PFD_2','PFD_3','PFD_4','PFD_5']})
Samples=pd.DataFrame({'Sam':['PFD_1','PFD_5']})
df['col2'] = np.where(df.col2.isin(Samples.Sam),'Yes' + df.col2, 'Non_'+ df.col2)
df['col2']

Outputs ..

0     YesPFD_1
1    Non_PFD_2
2    Non_PFD_3
3    Non_PFD_4
4     YesPFD_5
Name: col2, dtype: object

Upvotes: 5

Related Questions