nilsinelabore
nilsinelabore

Reputation: 5115

Replace entire column with a particular value in each group in Pandas

I want to replace values in Column1 in each Group with the value in Column1 where Column0 in that row begins with Date and Time :

df:

    Column0         Column1         Column2         Column3        Group 
1   Date and Time : 10/01/17,0900   NaN             NaN            A    * value to replace with
2   NaN             NaN             NaN             NaN            A
3   Name            NaN             NaN             NaN            A
                                    ...

1   NaN             NaN             02/06/17,1030   NaN            B
2   Date and Time : 02/06/17,1000   NaN             NaN            B    * value to replace with
3   Details         05/07/17,1330   NaN             NaN            B
4   NaN             01/08/17,1400   Date and Time : NaN            B
                                    ...

Expected output:

    Column0         Column1         Column2         Column3        Group 
1   Date and Time : 10/01/17,0900   NaN             NaN            A
2   NaN             10/01/17,0900   NaN             NaN            A
3   Name            10/01/17,0900   NaN             NaN            A
                                    ...

1   NaN             02/06/17,1000   02/06/17,1030   NaN            B
2   Date and Time : 02/06/17,1000   NaN             NaN            B
3   Details         02/06/17,1000   NaN             NaN            B
4   NaN             02/06/17,1000   Date and Time : NaN            B
                                    ...

Upvotes: 0

Views: 85

Answers (1)

jezrael
jezrael

Reputation: 862681

Select rows by condition Series.str.startswith first in boolean indexing, create Series by Group with select Column1 and last use Series.map:

s = (df[df['Column0'].str.startswith('Date and Time', na=False)]
       .set_index('Group')['Column1'])
df['Column1'] = df['Group'].map(s)

Upvotes: 3

Related Questions