如果基于前一行的条件产生“序列的真值是模糊的。使用a.empty、a.bool()、a.item()、a.any()或a.all()

2024-06-28 19:34:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有借款人身份证,银行身份证,到期日和贷款发放日期的贷款数据。我想知道,对于任何借款人来说,她以前的贷款是否在当前贷款发放之前尚未到期(多次借款)。如果是这样,我想生成一个列,其中包含从中取出上一笔尚未到期贷款的银行id。你知道吗

我的数据看起来像

df = pd.DataFrame({'month':[3,6,7,12,2,5,8,1],
              'borrower':[1,1,1,1,2,2,3,4],
              'bank':[1,1,2,3,3,3,4,5],
              'maturity':[9,18,19,24,14,17,14,13]})

我想在这一栏中补充:

df = pd.DataFrame({'month':[3,6,7,12,2,5,8,1],
              'borrower':[1,1,1,1,2,2,3,4],
              'bank':[1,1,2,3,3,3,4,5],
              'maturity':[9,18,19,24,14,17,14,13],
              'currently_borrowing':[np.nan,1,1,2,np.nan,3,np.nan,np.nan]})

我尝试了以下代码:

df = df.sort_values(['borrower','month'])
if ((df['bank'] == df['bank'].shift()) & (df['maturity'] >= df['maturity'].shift()) &(df['maturity'].shift() > df['month'])) :
    df['currently_borrowing'] = df['bank'].shift()
else : 
    df['currently_borrowing'] = np.nan

但我收到以下错误消息:

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我尝试添加.any().all(),但是新列只包含nan。你知道吗

非常感谢您的帮助!你知道吗


Tags: 数据dfshiftnp银行nanbank身份证
1条回答
网友
1楼 · 发布于 2024-06-28 19:34:09

IIUC,您可以创建一个掩码并使用np.where

print(df)

   bank  borrower  maturity  month
0     1         1         9      3
1     1         1        18      6
2     2         1        19      7
3     3         1        24     12
4     3         2        14      2
5     3         2        17      5
6     4         3        14      8
7     5         4        13      1

df = df.sort_values(['borrower','month'])

mask = ((df['borrower'] == df['borrower'].shift()) 
       & (df['maturity'] >= df['maturity'].shift()) 
       & (df['maturity'].shift() > df['month']))

df['current borrow'] = np.where(mask, df.bank.shift(), np.nan)

print(df)

   bank  borrower  maturity  month  currentborrow
0     1         1         9      3            NaN
1     1         1        18      6            1.0
2     2         1        19      7            1.0
3     3         1        24     12            2.0
4     3         2        14      2            NaN
5     3         2        17      5            3.0
6     4         3        14      8            NaN
7     5         4        13      1            NaN

你误解了if...else的适用性-它只适用于标量值,而不是pd.Series。这就是np.where更适合这里的原因。你知道吗

此外,您的掩码逻辑也有问题。第一个条件应该在borrower上完成,而不是在bank上完成。你知道吗

相关问题 更多 >