Created
July 31, 2019 17:50
-
-
Save douglascodes/e9bef5a83fd6491906fcee66f1b1d2b7 to your computer and use it in GitHub Desktop.
Example for assign Tuple result to two columns after .apply() in Pandas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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