0

For Pandas module in Python:

Suppose I have the following dataframe here:

      A    B
1    50    0
     50    1
     50    0
2    65    0
     65    0
     65    0
3    23    0
     23    0
     23    1

I want to change column B so that if any row that belongs to a specific index has a 1, then all rows belong to that index in B will be turn into 1.

output:
      A    B
1    50    1
     50    1
     50    1
2    65    0
     65    0
     65    0
3    23    1
     23    1
     23    1

Thanks in advance.

RichS
  • 117
  • 4

1 Answers1

1

Use:

df['B'] = df.groupby('A')['B'].transform('max')

For level:

df['B'] = df.groupby(level=0)['B'].transform('max')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252