Pandas:根据不同的列复制特定行的值

Hat*_*rax 5 python dataframe pandas

我想要实现的是,当 col2 中的一行有 1 时,只要 col1 中的行具有相同的名称,它就会将该 1 复制到 col2 中的所有其他值上。举个例子,如果数据框看起来像这样

col1  col2
xx      1
xx      0
xx      0
xx      0
yy      0
yy      0
yy      0
zz      0
zz      0
zz      1
Run Code Online (Sandbox Code Playgroud)

输出将是

col1  col2
xx      1
xx      1
xx      1
xx      1
yy      0
yy      0
yy      0
zz      1
zz      1
zz      1
Run Code Online (Sandbox Code Playgroud)

moz*_*way 6

使用groupby.transform('max')

df['col2'] = df.groupby('col1')['col2'].transform('max')
Run Code Online (Sandbox Code Playgroud)

输出:

  col1  col2
0   xx     1
1   xx     1
2   xx     1
3   xx     1
4   yy     0
5   yy     0
6   yy     0
7   zz     1
8   zz     1
9   zz     1
Run Code Online (Sandbox Code Playgroud)