python-3.x – 通过更改pandas中组内的列值来创建组
发布时间:2020-12-20 11:08:31 所属栏目:Python 来源:网络整理
导读:当Success或Failure列返回True值时,我想在每个Chat_id中创建组.如果成功或失败列的上一行中存在True值,则组的值会更改.我应该怎么做大熊猫呢.所以基本上,Group列是我想要创建的,但是chat_id,Success和Failure Column已经存在. +---------+-------+---------+
当Success或Failure列返回True值时,我想在每个Chat_id中创建组.如果成功或失败列的上一行中存在True值,则组的值会更改.我应该怎么做大熊猫呢.所以基本上,Group列是我想要创建的,但是chat_id,Success和Failure Column已经存在.
+---------+-------+---------+---------+ | Chat_id | Group | Success | Failure | +---------+-------+---------+---------+ | A | 0 | FALSE | FALSE | | A | 0 | FALSE | FALSE | | A | 0 | TRUE | FALSE | | A | 1 | FALSE | FALSE | | A | 1 | FALSE | TRUE | | A | 2 | FALSE | FALSE | | A | 2 | FALSE | FALSE | | B | 0 | FALSE | FALSE | | B | 0 | FALSE | FALSE | | B | 0 | FALSE | TRUE | | B | 1 | FALSE | FALSE | | B | 1 | FALSE | FALSE | | B | 1 | FALSE | FALSE | | C | 0 | FALSE | FALSE | | C | 0 | TRUE | FALSE | | C | 1 | FALSE | FALSE | | C | 1 | TRUE | FALSE | +---------+-------+---------+---------+ 尝试了以下,但似乎没有工作. def groupping(dfg): ind=0: for row in dfg: if row.Success==True or row.Failure==True: ind+=1 return ind df.groupby(chat_id).apply(lambda x: grouping(x)) 解决方法
它更像是
df[['Success','Failure']].sum(1).gt(0).groupby(df.Chat_id).cumsum() Out[273]: 0 0.0 1 0.0 2 1.0 3 1.0 4 2.0 5 2.0 6 2.0 7 0.0 8 0.0 9 1.0 10 1.0 11 1.0 12 1.0 13 0.0 14 1.0 15 1.0 16 2.0 dtype: float64 修复你的代码 def grouping(dfg): ind=0 l=[] for _,row in dfg.iterrows(): if row.Success==True or row.Failure==True: ind+=1 l.append(ind) else : l.append(ind) return pd.Series(l) df.groupby('Chat_id').apply(grouping) Out[292]: Chat_id A 0 0 1 0 2 1 3 1 4 2 5 2 6 2 B 0 0 1 0 2 1 3 1 4 1 5 1 C 0 0 1 1 2 1 3 2 dtype: int64 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |