Question: I have a df with customer\_id, year, order and a few other but unimportant columns. Every time when i get a new order, my code creates a new row, so there can be more than one row for each customer\_id. I want to create a new column 'actually', which includes 'True' if a customer\_id bought in 2020 or 2021. My Code is:

```
#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"]

```

This works fine, but quite slow. I want to use Pandas groupby function, but didnt find a working way so far. Also i avoid loops. Anyone an idea?

Answer: 
you can create the column name 'Actually' something like this.

```
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)

```
You can use apply method, to avoid loops:

```
df['actually']=df['customer_id'].apply(lambda x: df[df.customer_id==x]['year'].str.contains('2020').any() or df[df.customer_id==x]['year'].str.contains('2021').any())

```