[英]Pandas: Create a new column returning True or False if all the other values in the row are empty strings
[英]Pandas: How to create True/False column that check existing row with certain values in the previous weeks?
能否請你幫忙?
這是我的 dataframe。
分店名稱 | 周開始 | 產品 |
---|---|---|
蘋果商店 | 2021 年 1 月 11 日 00:00:00 | 蘋果 iPhone XR 64 GB |
蘋果商店 | 2021 年 1 月 11 日 00:00:00 | 蘋果 iPhone 11 128 GB |
T移動 | 2021 年 1 月 11 日 00:00:00 | 蘋果 iPhone 13 Pro 256 GB |
T移動 | 2021 年 1 月 11 日 00:00:00 | 蘋果 iPhone 12 256 GB |
蘋果商店 | 2021 年 8 月 11 日 00:00:00 | 蘋果 iPhone XR 64 GB |
蘋果商店 | 2021 年 8 月 11 日 00:00:00 | 蘋果 iPhone 11 128 GB |
T移動 | 15/11/2021 00:00:00 | 蘋果 iPhone 13 Pro 256 GB |
T移動 | 15/11/2021 00:00:00 | 蘋果 iPhone 12 256 GB |
蘋果商店 | 15/11/2021 00:00:00 | 蘋果 iPhone XR 64 GB |
蘋果商店 | 15/11/2021 00:00:00 | 蘋果 iPhone 11 128 GB |
T移動 | 22/11/2021 00:00:00 | 蘋果 iPhone 13 Pro 256 GB |
T移動 | 22/11/2021 00:00:00 | 蘋果 iPhone 12 256 GB |
蘋果商店 | 22/11/2021 00:00:00 | 蘋果 iPhone XR 64 GB |
蘋果商店 | 22/11/2021 00:00:00 | 蘋果 iPhone 11 128 GB |
我想創建一個新列,告訴我在過去 3 周(包括過去 3 周)內某個商店中存在特定產品。 如果最近 3 周某個商店沒有產品,則為假。
分店名稱 | 周開始 | 產品 | 存在前 3 周 |
---|---|---|---|
蘋果商店 | 22/11/2021 00:00:00 | 蘋果 iPhone XR 64 GB | 真的 |
蘋果商店 | 22/11/2021 00:00:00 | 蘋果 iPhone 11 128 GB | 真的 |
T移動 | 22/11/2021 00:00:00 | 蘋果 iPhone 13 Pro 256 GB | 錯誤的 |
T移動 | 22/11/2021 00:00:00 | 蘋果 iPhone 12 256 GB | 錯誤的 |
我怎樣才能做到這一點?
我試過無濟於事:
def prev_3week(x):
if (x - pd.DateOffset(weeks=3) in x.values) & (x - pd.DateOffset(weeks=2) in x.values) & (x - pd.DateOffset(weeks=1) in x.values):
return True #considering day greater than 14 as third week
else:
return False
df['Exists prev 3week'] = df.groupby(['Branch name'])['WeekStart'].apply(lambda x: prev_3week(x)).reset_index(drop=True)
我假設您的 dataframe 已經按WeekStart
列排序並且數據類型為datetime64
。
嘗試:
# If it's not already the case, comment out this lines
# df['WeekStart'] = pd.to_datetime(df['WeekStart'], dayfirst=True)
# df = df.sort_values('WeekStart')
consecutive_week = lambda x, n: x.sub(x.shift()).eq(pd.Timedelta(days=7))[-n:].all()
out = df.groupby(['Branch name', 'Product']).agg(**{
'WeekStart': ('WeekStart', 'last'),
'Exists prev 3week': ('WeekStart', lambda x: consecutive_week(x, n=3)),
'Exists prev 2week': ('WeekStart', lambda x: consecutive_week(x, n=2))
}).reset_index()
Output:
>>> out
Branch name Product WeekStart Exists prev 3week Exists prev 2week
0 Apple Store Apple Iphone 11 128 gb 2021-11-22 True True
1 Apple Store Apple Iphone XR 64 gb 2021-11-22 True True
2 T mobile Apple Iphone 12 256 gb 2021-11-22 False False
3 T mobile Apple Iphone 13 Pro 256 gb 2021-11-22 False False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.