简体   繁体   中英

How can I compare part of the string of a cell on a row with another string on the same row and swap them places if they meet my conditions?

I have the following Data Frame:

import pandas as pd

df =  {'Country': ['A','A','B','B','B'],'MY_Product': ['NS_1',  'SY_1','BMX_3','NS_5','NK'],'Cost': [5, 35,34,45,9],'Competidor_Country_2': ['A', 'A' ,'B','B','B'],'Competidor_Product_2': ['BMX_2','TM_0','NS_6','SY_8','NA'],'Competidor_Cost_2': [35, 20,65,67,90]}

df_new = pd.DataFrame(df,columns=['Country',  'MY_Product',  'Cost','Competidor_Country_2','Competidor_Product_2','Competidor_Cost_2'])
print(df_new)

Information:

  1. My products must start with "NS","SY", "NK" or "NA";
  2. In the first three columns is represented informations of my products and in the last three the competitor's product
  3. I did not put all examples to simplify the exercise

Problem:

  1. As you can see in the third row, there is a product that is not mine ("BMX_3") and the competidor is one of mine...So I would like to replace not only the pruduct but the other competidor's columns too, thus leaving the first three columns with my product and the last 3 with the competitor's

Considerations:

  1. if the two products in the line are my products (last row for exemple), I don't need to do anything (but if possible leave a "comment code" to delete this comparison will help me, just in case)

If I understand you right, you want to swap values of the 3 columns if the product in MY_Product isn't yours :

# create a mask
mask = ~df_new.MY_Product.str.contains(r"^(?:NS|SY|NK|NA)")

# swap the values of the three columns:
vals = df_new.loc[mask, ["Country", "MY_Product", "Cost"]].values

df_new.loc[mask, ["Country", "MY_Product", "Cost"]] = df_new.loc[
    mask, ["Competidor_Country_2", "Competidor_Product_2", "Competidor_Cost_2"]
].values

df_new.loc[
    mask, ["Competidor_Country_2", "Competidor_Product_2", "Competidor_Cost_2"]
] = vals

# print the dataframe
print(df_new)

Prints:

  Country MY_Product  Cost Competidor_Country_2 Competidor_Product_2  Competidor_Cost_2
0       A       NS_1     5                    A                BMX_2                 35
1       A       SY_1    35                    A                 TM_0                 20
2       B       NS_6    65                    B                BMX_3                 34
3       B       NS_5    45                    B                 SY_8                 67
4       B         NK     9                    B                   NA                 90

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM