SHARE
TWEET

Untitled

a guest Jun 19th, 2019 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2. import pandas as pd
  3.  
  4. df = pd.DataFrame({'Type': np.random.choice(['A', 'B', 'C', 'D'], 100),
  5.                    'Var1': np.random-randn(100),
  6.                    'Var2': np.linpace(30, 200, 100)})
  7.      
  8. # 1. Assignment depending on other columns
  9. df['Var3'] = df.Var2 / df.Var1  # "Normal" assignment
  10. df.assign(Var3 = df.Var2 / df.Var1)  # Assign statement
  11.  
  12. # 2. Assignment based on a conditional function:
  13. df['CondVar'] = df.apply(lambda x: x['Var1'] * np.sin(x['Var2'] if x['Type'] == 'A' else 2, axis='columns')  # Via apply
  14. df.assign(CondVar = lambda x: x['Var1'] * np.sin(x['Var2'] if x['Type'] == 'A' else 2, axis='columns')  # assign statement
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top