Sep 28, 2022

[Python] to compare/calculate Pandas columns

to compare Pandas columns, 
    print(df['Column1'].equals(df['Column2'])) 

if df['Column1'] is equal to df['Column2'], it will return "True" otherwise "False" 


to calculate/assign values,
    print(df['Column1'] + df['Column2']) 

import numpy as np
import pandas as pd

a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])

df['que'] = np.where((df['one'] >= df['two']) & (df['one'] <= df['three']), df['one'], np.nan)

result will look like:
          one  two three  que
   0     10    1.2   4.2    10
   1      5     70    0.03  NaN
   2      8     5      0       NaN

No comments:

Post a Comment