gpt4 book ai didi

python - Pandas - 自上次交易以来的计数

转载 作者:行者123 更新时间:2023-11-28 22:16:02 25 4
gpt4 key购买 nike

我有一个包含货币交易记录的数据框(称之为 txn_df),以下是此问题中的重要列:

txn_year    txn_month   custid  withdraw    deposit
2011 4 123 0.0 100.0
2011 5 123 0.0 0.0
2011 6 123 0.0 0.0
2011 7 123 50.1 0.0
2011 8 123 0.0 0.0

还假设我们这里有多个客户。 withdrawdeposit 两者的值都为 0.0 表示没有发生任何交易。我想要做的是生成一个新列,指示自发生交易以来已经发生了多少个月。类似这样的东西:

txn_year    txn_month   custid  withdraw    deposit     num_months_since_last_txn
2011 4 123 0.0 100.0 0
2011 5 123 0.0 0.0 1
2011 6 123 0.0 0.0 2
2011 7 123 50.1 0.0 3
2011 8 123 0.0 0.0 1

到目前为止,我能想到的唯一解决方案是在 withdrawdeposit 的值 > 0.0,但我无法从那里继续。

最佳答案

解决这个问题的一种方法,

df['series'] =  df[['withdraw','deposit']].ne(0).sum(axis=1)
m = df['series']>=1

正如@Chris A 评论的那样,

m = df[['withdraw','deposit']].gt(0).any(axis=1) #replacement for above snippet,

df['num_months_since_last_txn'] = df.groupby(m.cumsum()).cumcount()
df.loc[df['num_months_since_last_txn']==0,'num_months_since_last_txn']=(df['num_months_since_last_txn']+1).shift(1).fillna(0)
print df

输出:

   txn_year  txn_month  custid  withdraw  deposit
0 2011 4 123 0.0 100.0
1 2011 5 123 0.0 0.0
2 2011 6 123 0.0 0.0
3 2011 7 123 50.1 0.0
4 2011 8 123 0.0 0.0
txn_year txn_month custid withdraw deposit num_months_since_last_txn
0 2011 4 123 0.0 100.0 0.0
1 2011 5 123 0.0 0.0 1.0
2 2011 6 123 0.0 0.0 2.0
3 2011 7 123 50.1 0.0 3.0
4 2011 8 123 0.0 0.0 1.0

解释:

  1. 要确定交易是否发生,请使用 ne 和求和以获取二进制值。
  2. 当事务为 1 时,使用 groupbycumsumcumcount 从 0,1,2...n 创建系列。
  3. 使用 .loc 重新排列 0 的值>

注意:可能是我添加了更复杂的内容来解决这个问题。但它会给你一个想法和方法来解决这个问题。

考虑客户ID的解决方案,

df=df.sort_values(by=['custid','txn_month'])
mask=~df.duplicated(subset=['custid'],keep='first')
m = df[['withdraw','deposit']].gt(0).any(axis=1)
df['num_months_since_last_txn'] = df.groupby(m.cumsum()).cumcount()
df.loc[df['num_months_since_last_txn']==0,'num_months_since_last_txn']=(df['num_months_since_last_txn']+1).shift(1)
df.loc[mask,'num_months_since_last_txn']=0

示例输入:

   txn_year  txn_month  custid  withdraw  deposit
0 2011 4 123 0.0 100.0
1 2011 5 123 0.0 0.0
2 2011 4 1245 0.0 100.0
3 2011 5 1245 0.0 0.0
4 2011 6 123 0.0 0.0
5 2011 7 1245 50.1 0.0
6 2011 7 123 50.1 0.0
7 2011 8 123 0.0 0.0
8 2011 6 1245 0.0 0.0
9 2011 8 1245 0.0 0.0

示例输出:

   txn_year  txn_month  custid  withdraw  deposit  num_months_since_last_txn
0 2011 4 123 0.0 100.0 0.0
1 2011 5 123 0.0 0.0 1.0
4 2011 6 123 0.0 0.0 2.0
6 2011 7 123 50.1 0.0 3.0
7 2011 8 123 0.0 0.0 1.0
2 2011 4 1245 0.0 100.0 0.0
3 2011 5 1245 0.0 0.0 1.0
8 2011 6 1245 0.0 0.0 2.0
5 2011 7 1245 50.1 0.0 3.0
9 2011 8 1245 0.0 0.0 1.0

考虑客户 ID 的说明,

  1. 以上代码基于 [1,1] 之间的区间工作。因此,要制作相同的格式,请按 cust_id 和 txn_month 对 df 进行排序,将来您可以添加 txn_year。
  2. fillna(0),不会在这里工作,因为 shift 不会为下一个客户创建 NaN。重置为 0 查找重复的客户 ID 并将第一个值替换为 0。

关于python - Pandas - 自上次交易以来的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52494999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com