單個列我有以下大熊貓數據幀命名matches
:熊貓:變換行到基於狀態
id | name | age
1 | a | 19
1 | b | 25
2 | c | 19
2 | d | 22
我使用groupby
+ count()
,如果某一列(age
)的值滿足條件( x < 21
)。結果被寫入到一個新的列(new_col
):
matches['new_col'] = matches.groupby(['id'])['age'].transform(lambda x: x[x < 21].count())
然後將數據幀是這樣的:
id | name | age | new_col
1 | a | 19 | 1
1 | b | 25 | 1
2 | c | 19 | 2
2 | d | 18 | 2
現在我想將結果輸出更可讀的方式,也就是說,應滿足條件(年齡爲<21)的每行的name
列應寫入新列,例如result
。
我希望這樣的事情(但是,也有可能通過其他方式來實現這一目標甚至做THI已經在第一步中,在那裏我加new_col
):
id | name | age | new_col | result
1 | a | 19 | 1 | a
1 | b | 25 | 1 | a
2 | c | 19 | 2 | c,d
2 | d | 18 | 2 | c,d
最後一步(添加result
專欄)是我現在堅持的地方。