如何对Python Pandas dataframe列执行数学操作,但前提是满足特定条件?

2024-06-01 11:44:21 发布

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

我有一个Pandas数据框,我正在使用它,我只需要将某一列中大于800的所有值除以100。换言之,如果“信用评分”列中的值大于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,但不想用其他的。我希望新的有效值替换旧的无效值。另外,一个新的栏目,如“信用评分”也会起作用。我对Python和熊猫还不太熟悉,所以非常感谢您的帮助。


Tags: 数据idpandascolumn评分分数scorecredit
3条回答

您可以使用^{}

df.credit_score = df.credit_score.mask( df.credit_score > 800, df.credit_score/ 100)

^{}

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

我会用Pandas boolean indexing

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

您可以使用^{}。它接受一个函数并将其应用于序列中的每个元素。请注意,它没有就位,您需要将它返回的序列重新分配给新列或同一列。

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)

相关问题 更多 >