熊猫使用groupby创建新列并避免循环

罗宾·穆勒

我有一个带有customer_id,year,order和其他一些但不重要的列的df。每当我收到新订单时,我的代码都会创建一个新行,因此每个customer_id可以有多个行。我想创建一个“实际”新列,如果customer_id是在2020年或2021年购买的,则包括“ True”。我的代码是:

#Run through all customers and check if they bought in 2020 or 2021
investors = df["customer_id"].unique()
df["actually"] = np.nan
for i in investors:
    selected_df = df.loc[df["customer_id"] == i]
    for year in selected_df['year'].unique():
        if "2021" in str(year) or "2020" in str(year):
            df.loc[df["customer_id"] == i, "actually"] = "True"
            break
#Want just latest orders / customers
df = df.loc[df["actually"] == "True"]

这工作正常,但速度很慢。我想使用Pandas groupby函数,但到目前为止没有找到一种可行的方法。我也避免循环。有人知道吗?

赫曼什·维玛(Hemansh Verma)

您可以像这样创建“实际”列名称。

list1=df['Customer_id'][df.year==2020].unique()
list2=df['Customer_id'][df.year==2021].unique()
df['Actually']=df['Customer_id'].apply( lambda x : x in list1 or x in list2)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章