Skip to content Skip to sidebar Skip to footer

How To Add A New Column And Fill It Up With A Specific Value Depending On Another Column's Series?

I'm new to Pandas but thanks to Add column with constant value to pandas dataframe I was able to add different columns at once with c = {'new1': 'w', 'new2': 'y', 'new3': 'z'} df.

Solution 1:

If I understand you correctly, you want GroupBy.transform.any

First we create a boolean array by checking which rows in Product are Bag with Series.eq. Then we GroupBy on this boolean array and check if any of the values are True. We use transform to keep the shape of our initial array so we can assign the values back.

df['ind'] = df['Product'].eq('Bag').groupby(df['Order']).transform('any').astype(int)

   Order  Orderline   Product  ind
010    Laptop    1111       Bag    1212     Mouse    1320  Keyboard    0430    Laptop    0531     Mouse    0

Post a Comment for "How To Add A New Column And Fill It Up With A Specific Value Depending On Another Column's Series?"