簡體   English   中英

如何在Python Pandas數據幀列上執行數學運算,但僅限於滿足某個條件?

[英]How do I perform a math operation on a Python Pandas dataframe column, but only if a certain condition is met?

我有一個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的新手,所以非常感謝任何幫助。

我使用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

你可以使用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

您可以使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM