numpy 元组解包和np.max()给出意外值

vs3odd8k  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(132)

我有一个数据集,我试图过滤和应用调整值使用元组。

df = pd.DataFrame({
    'loannum': ['1', '2', '3', '4'],
    'or_dep': [250000, 650000, 1000000, 300000]
})

loan2adj = [('1', 50000), ('3', 250000), ('2', 100000)]

我的预期输出看起来像这样。

loannum      or_dep
1            200000
2            550000
3            750000
4            300000

这是我用来解包元组并应用调整值的逻辑。

for loan, adj_amt in loan2adj:
    df.loc[df['loannum'] == loan, 'or_dep'] = np.max(df['or_dep'] - adj_amt, 0)

这段代码产生了一些不寻常的值。

loannum     or_dep
1           950000
2           550000
3           750000
4           300000

贷款3和贷款4正在正确地返回。贷款4不应该有调整,贷款3正在正确地调整。我如何才能实现期望的产出?

2hh7jdfx

2hh7jdfx1#

问题是,当您执行np.max(df['or_dep'] - adj_amt, 0)时,您没有选择想要的行。
要修复它,只需:

for loan, adj_amt in loan2adj:
    df.loc[df['loannum'] == loan, 'or_dep'] = np.max(df.loc[df['loannum'] == loan, 'or_dep'] - adj_amt, 0)

您可能应该使用loannum列作为索引来简化locs:

df.set_index("loannum", inplace=True)
for loan, adj_amt in loan2adj:
    df.loc[loan, 'or_dep'] = max(df.loc[loan, 'or_dep'] - adj_amt, 0)

相关问题