给定一个示例数据帧:
example_df = pd.DataFrame({"app_id": [1,2,3,4,5,6] ,
"payment_date":["2021-01-01", "2021-02-01", "2020-03-02", "2020-04-05", "2020-01-05","2020-01-04"],
"user_id": [12,12,12,13,13,13],
"application_date":["2021-02-01", "2021-02-01", "2020-03-02", "2020-04-05", "2020-01-05", "2020-01-04"] , "flag": [1,0,0,1,0,1], "order_column": [1,2,3,4,5, 6]})
应该做的是:
- 我将用一个例子解释我想做什么:
- 遍历所有行
- 如果标志列等于1,请执行以下操作
- 对于第一行,CCD_ 1列是1,并且该行的CCD_ 2是12。查看
user_id
=12的所有实例,并将它们的application_date
与第一行的payment_date
进行比较。我们看到第二行具有比第一行的payment_date
大的application_date
。则第一行的标签为1。第三行也属于user_id
=12,但其application_date
不大于第一行的payment_date。如果有一个或多个观测值的flag
0大于第一行的payment_date
,则第一行的总标签为1。如果没有这样的观察结果,则总体标签为0
我用iterrows为此编写了代码,但我想要一个更紧凑的矢量化解决方案,因为在较大的数据集中,iterrrows可能会很慢。像
example_df.groupby("something").filter(lambda row: row. ...)
我的代码是:
labels_dict = {}
for idx, row in example_df.iterrows():
if row.flag == 1:
app_id = row.app_id
user_id = row.user_id
user_df = example_df[example_df.user_id == user_id]
labelss = []
for idx2, row2 in user_df.iterrows():
if (row2.order_column != row.order_column) & (row.payment_date < row2.application_date):
label = 1
labelss.append(label)
elif (row2.order_column != row.order_column) & (row.payment_date >= row2.application_date):
label = 0
labelss.append(label)
labels_dict[app_id] = labelss
final_labels = {}
for key, value in labels_dict.items():
if 1 in value:
final_labels[key] = 1
else:
final_labels[key] = 0
final_labels
是预期输出。基本上,根据我解释的标准,我要求将flag
=1的所有行标记为1或0。
期望输出:
{1: 1, 4: 0, 6: 1}
Here keys are app_id and values are labels (either 0 or 1)
我首先用flag
中只有1的行构建一个临时数据帧,并将其与user_id
上的完整数据帧合并。
然后,如果application_date大于payment_date,并且原始app_id与on-from-temp(即不同的行(不同,我将添加一个新的布尔列,该列为true
最后,计算每个app_id的真实值的数量就足够了,如果该数量大于0,则给出1。
Pandas代码可能是:
tmp = example_df.loc[example_df['flag'] == 1,
['app_id', 'user_id', 'payment_date']]
tmp = tmp.merge(example_df.drop(columns = 'payment_date'), on='user_id')
tmp['k'] = ((tmp['app_id_x'] != tmp['app_id_y'])
& (tmp['application_date'] > tmp['payment_date']))
d = (tmp.groupby('app_id_x')['k'].sum() != 0).astype('int').to_dict()
对于您的数据,它会如预期那样给出:
{1: 1, 4: 0, 6: 1}
(i(将所有日期转换为日期时间对象
(ii(CCD_ 16〃;user_id";并且对于每个组;payment_ date";使用CCD_ 17并将其变换为整个DataFrame。然后将其与";application_ date";s使用CCD_ 18(小于(。
(iii(CCD_ 19〃;user_id";再次查找满足条件的条目数量,并根据总和是否大于1来分配值。
example_df['payment_date'] = pd.to_datetime(example_df['payment_date'])
example_df['application_date'] = pd.to_datetime(example_df['application_date'])
example_df['flag_cumsum'] = example_df['flag'].cumsum()
example_df['first_payment_date < application_date'] = (example_df
.groupby(['flag_cumsum','user_id'])['payment_date']
.transform('first')
.lt(example_df['application_date']))
out = (example_df.groupby('flag_cumsum').agg({'app_id':'first',
'first_payment_date < application_date':'sum'})
.set_index('app_id')['first_payment_date < application_date']
.gt(0).astype(int)
.to_dict())
输出:
{1: 1, 4: 0}