python pandas operations on columns

前端 未结 4 432
北海茫月
北海茫月 2021-02-06 11:52

Hi I would like to know the best way to do operations on columns in python using pandas.

I have a classical database which I have loaded as a dataframe, and I often have

4条回答
  •  鱼传尺愫
    2021-02-06 12:33

    simplest according to me.

    from random import randint, randrange, uniform
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'a':randrange(0,10),'b':randrange(10,20),'c':np.random.randn(10)})
    
    #If colC > 0,5, then ColC = ColB - Cola 
    df['c'][df['c'] > 0.5] = df['b'] - df['a']
    

    Tested, it works.

    a   b   c
    2  11 -0.576309
    2  11 -0.578449
    2  11 -1.085822
    2  11  9.000000
    2  11  9.000000
    2  11 -1.081405
    

提交回复
热议问题