2 回答

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
這是使用的一種方法np.select
:
conds = [df.Color.eq('red'), df.Color.eq('purple')]
df['col3'] = np.select(conds, [1,0], '')
df['col3'] = df.groupby('ID').col3.transform('max')
或者我們可以改為將 a 設(shè)置nan為默認(rèn)值,并使用 進(jìn)行轉(zhuǎn)換first:
df['col3'] = np.select(conds, [1,0], np.nan)
df['col3'] = df.groupby('ID').col3.transform('first').fillna('')
print(df)
ID Color col3
0 1 red 1
1 1 blue 1
2 1 yellow 1
3 2 blue 0
4 2 purple 0
5 3 yellow
6 3 green
請注意,前一種方法利用了以下優(yōu)勢:
max('', '0')
# '0'
max('', '1')
# '1'

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊
numpy如果您出于任何原因不想使用,這里有一個(gè)替代方案:
df['col3'] = df.set_index('ID')['Color'].apply({'red': 1, 'purple': 0}.get).groupby(level=0).transform('max').fillna('').reset_index(drop=True)
ID Color col3
0 1 red 1
1 1 blue 1
2 1 yellow 1
3 2 blue 0
4 2 purple 0
5 3 yellow
6 3 green
添加回答
舉報(bào)