如何在Python Pandas数据帧列上执行数学运算,但只有在满足特定条件时才执行?

6

我有一个 Pandas 的数据框,现在需要将某一列中大于 800 的值除以 100。也就是说,如果 'credit_score' 列中的值大于 800,则可以假设数据在小数点左侧有两个额外的数字。例如...

id    credit_score    column_b    column_c
0     750             ...         ...
1     653             ...         ...
2     741             ...         ...
3     65100           ...         ...
4     73500           ...         ...
5     565             ...         ...
6     480             ...         ...
7     78900           ...         ...
8     699             ...         ...
9     71500           ...         ...

我想将第3、4、7和9行的信用评分除以100,但不包括其他行。我希望新的有效值替换旧的无效值。或者,一个名为“credit_score_fixed”的新列也可以起到同样的作用。我对Python和Pandas比较陌生,所以非常感谢任何帮助。

3个回答

8
你可以使用 mask 方法:
df.credit_score = df.credit_score.mask( df.credit_score > 800, df.credit_score/ 100)

或者使用 numpy.where:
df.credit_score = np.where( df.credit_score > 800, df.credit_score/ 100, df.credit_score)

print (df)
   id  credit_score    col   col1
0   0           750  750.0  750.0
1   1           653  653.0  653.0
2   2           741  741.0  741.0
3   3         65100  651.0  651.0
4   4         73500  735.0  735.0
5   5           565  565.0  565.0
6   6           480  480.0  480.0
7   7         78900  789.0  789.0
8   8           699  699.0  699.0
9   9         71500  715.0  715.0

对我来说,“掩码”是最直观的解决方案,而且完美地起作用了。谢谢! - ScottP

4

我会使用Pandas布尔索引:

In [193]: df.loc[df.credit_score > 800, 'credit_score'] /= 100

In [194]: df
Out[194]:
    credit_score
id
0          750.0
1          653.0
2          741.0
3          651.0
4          735.0
5          565.0
6          480.0
7          789.0
8          699.0
9          715.0

这个完美地运行了,谢谢!不过你能为我澄清一下 "/=" 与仅使用 "/" 有何不同吗? - ScottP
@ScottP,a /= 2 等同于 a = a / 2 - MaxU - stand with Ukraine

4

您可以使用Series.apply方法。它接受一个函数并将其应用于系列中的每个元素。请注意,它不是原地操作,您需要重新分配它返回的系列,无论是到一个新的列还是到同一列。

def fix_scores(score):
    return score / 100 if score > 800 else score
    # same as
    # if score > 800:
    #      return score / 100
    # return score

df['credit_score_fixed'] = df['credit_score'].apply(fix_scores)

太棒了,非常感谢! - ScottP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接