groupby,然后基于另一列设置列值(索引器太多)

2024-05-17 17:45:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

    updated_at   type      source
0   2017-01-01   User     
1   2017-01-01   Inbound
2   2017-01-02   User
3   2017-01-02   Outbound
4   2017-01-03   Outbound
5   2017-01-03   User

我需要去掉type != User所在的行,然后将type == User所在行的源代码设置为要去掉的行的type。到目前为止,我已经尝试过做groupby('updated_at),但是遇到了在副本上设置值的错误。而且,groupby('updated_at')总是只返回两行。你知道吗

下面是我想要的结果:

    updated_at   type      source
0   2017-01-01   User      Inbound
2   2017-01-02   User      Outbound
5   2017-01-03   User      Outbound

注:我有37万排


Tags: 数据source源代码outboundtype错误副本at
2条回答

如果确定目标行是连续的,可以使用shift

df["source"]=df["type"].shift(-1)

然后过滤出type=="User"


编辑

因为这些线不是连续的,不像你的样本

df=df.sort_values(["updated_at", "type"])

这将保证一个时间戳类型总是(1)入站/出站(2)用户。 然后:

df["source"]=df["type"].shift()

然后过滤出type=="User"

拆分数据帧并使用相同的索引对其进行标准化。 然后从源代码中宣布源列

user = df.loc[df.type == 'User',:]
user.set_index('updated_at')
bound = df.loc[df.type != 'User',:]
bound.set_index('updated_at')
user['source'] = bound.type

相关问题 更多 >