Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace the column value with certain conditions

My dataframe looks like the below and name of the dataframe is "Assert_data"

System_Name  Type
ABC          Test-3451
BCS          Dev-2323
ASD          Dev-1213
FGS          Prod-1212
ASC          Tes-1244

Need help to replace the column value , If the Type column has a value as "Prod" , It should be replaced to "Production"

Likewise for Dev ==> Development & Tes ==> Test

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tired the following coding , But it throws "ValueError: either both or neither of x and y should be given"

df['Instance_type'] = np.where(Assert_data['Type'].str.contains("Prod"), "Production",
                                np.where(Assert_data['Type'].str.contains("Dev"), "Development",
                                np.where(Assert_data['Type'].str.contains("Tes"), "Test")))

Tried using pd.np.where – Same error message.

>Solution :

For last np.where is missing value y – if not match any condition:

Assert_data['Instance_type'] = np.where(Assert_data['Type'].str.contains("Prod"), "Production",
                               np.where(Assert_data['Type'].str.contains("Dev"), "Development",
                               np.where(Assert_data['Type'].str.contains("Tes"), "Test", None)))

print (Assert_data)
  System_Name       Type Instance_type
0         ABC  Test-3451          Test
1         BCS   Dev-2323   Development
2         ASD   Dev-1213   Development
3         FGS  Prod-1212    Production
4         ASC   Tes-1244          Test

Or use numpy.select:

Assert_data['Instance_type'] = np.select([Assert_data['Type'].str.contains("Prod"),
                                          Assert_data['Type'].str.contains("Dev"),
                                          Assert_data['Type'].str.contains("Tes")],
                                         [ "Production","Development","Test"],
                                         default=None)

Or use Series.str.extract with Series.map:

d = {'Prod': "Production","Dev":"Development","Tes":"Test"}

Assert_data['Instance_type'] = Assert_data['Type'].str.extract(f'({"|".join(d)})', expand=False).map(d)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading