Skip to content

Instantly share code, notes, and snippets.

@douglascodes
Created July 31, 2019 17:50
Show Gist options
  • Save douglascodes/e9bef5a83fd6491906fcee66f1b1d2b7 to your computer and use it in GitHub Desktop.
Save douglascodes/e9bef5a83fd6491906fcee66f1b1d2b7 to your computer and use it in GitHub Desktop.
Example for assign Tuple result to two columns after .apply() in Pandas
import pandas as pd
import random
def avg(a, b):
return (a+b)/2
def diff(a, b):
return abs(a-b)
def get_stats(a, b):
return avg(a, b), diff(a, b)
rand_array = lambda i: [random.randint(0, 100) for i in range(0, i)]
df = pd.DataFrame({'i': range(0, 100),
'a': rand_array(100),
'b': rand_array(100)}).set_index('i')
df[['avg', 'diff']] = df.apply(lambda x: get_stats(x['a'],
x['b']),
axis=1,
result_type='expand')
df.to_csv('out.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment