Python 如果在过去N天内满足条件,则创建新列
我有这样一个数据帧: 时间戳 价值 身份证件 2020-12-16 25 1. 2020-12-17 45 1. 2020-12-31 40 1. 2021-01-31 37 1. 2020-12-15 12 2. 2020-12-16 78 2.Python 如果在过去N天内满足条件,则创建新列,python,pandas,Python,Pandas,我有这样一个数据帧: 时间戳 价值 身份证件 2020-12-16 25 1. 2020-12-17 45 1. 2020-12-31 40 1. 2021-01-31 37 1. 2020-12-15 12 2. 2020-12-16 78 2. 因为您的计算需要排序,所以我们可以避免分组。排序,获取行差,并使用跨组的值(即每个ID的最早行),其中where到NaN。因为您希望第一个差异与'2020-12-15'相关,我们可以使用fillna查找与该日期的差异,并使用np.where根据您的条
因为您的计算需要排序,所以我们可以避免分组。排序,获取行差,并使用跨组的值(即每个ID的最早行),其中
where
到NaN
。因为您希望第一个差异与'2020-12-15'
相关,我们可以使用fillna
查找与该日期的差异,并使用np.where
根据您的条件分配字符串值
import pandas as pd
import numpy as np
df['timestamp'] = pd.to_datetime(df['timestamp'])
df = df.sort_values(['id', 'timestamp'])
s = (df['timestamp'].diff()
.where(df['id'].eq(df['id'].shift()))
.fillna(df['timestamp'] - pd.to_datetime('2020-12-15')))
#0 1 days
#1 1 days
#2 14 days
#3 31 days
#4 0 days
#5 1 days
df['outcome'] = np.where(s <= pd.Timedelta(25, 'D'), 'yes', 'no')
# timestamp value id outcome
#0 2020-12-16 25 1 yes
#1 2020-12-17 45 1 yes
#2 2020-12-31 40 1 yes
#3 2021-01-31 37 1 no
#4 2020-12-15 12 2 yes
#5 2020-12-16 78 2 yes
将熊猫作为pd导入
将numpy作为np导入
df['timestamp']=pd.to_datetime(df['timestamp']]
df=df.sort_值(['id','timestamp'])
s=(df['timestamp'].diff()
.where(df['id'].eq(df['id'].shift()))
.fillna(df['timestamp']-pd.to_datetime('2020-12-15'))
#0.1天
#1天
#2 14天
#3天31天
#40天
#5天1天
df['outcome']=np.其中(s适用条件,如果
1.一组连续天数之间的差值小于15
或
2.组中的第一项等于“是”。不满足任何条件的任何其他元素等于“否”
import numpy as np
df['outcome']=np.where(df.groupby('id.')['timestamp'].transform('diff').dt.days.lt(15)|~df['id.'].duplicated(keep='first'),'yes','no')
timestamp value id. outcome
0 2020-12-16 25.0 1.0 yes
1 2020-12-17 45.0 1.0 yes
2 2020-12-31 40.0 1.0 yes
3 2021-01-31 37.0 1.0 no
4 2020-12-15 12.0 2.0 yes
5 2020-12-16 78.0 2.0 yes