pandas apply multiple columns code example

Example 1: drop multiple columns pandas

yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)

Example 2: python add multiple columns to pandas dataframe

# Basic syntax:
df[['new_column_1_name', 'new_column_2_name']] = pd.DataFrame([[np.nan, 'word']], index=df.index)
# Where the columns you're adding have to be pandas dataframes

# Example usage:
# Define example dataframe:
import pandas as pd
import numpy as np
df = pd.DataFrame({
    'col_1': [0, 1, 2, 3],
    'col_2': [4, 5, 6, 7]
})

print(df)
   col_1  col_2
0      0      4
1      1      5
2      2      6
3      3      7

# Add several columns simultaneously:
df[['new_col_1', 'new_col_2', 'new_col_3']] = pd.DataFrame([[np.nan, 42, 'wow']], index=df.index)
print(df)
   col_1  col_2  new_col_1  new_col_2 new_col_3
0      0      4        NaN         42       wow
1      1      5        NaN         42       wow
2      2      6        NaN         42       wow
3      3      7        NaN         42       wow

# Note, this isn't much more efficient than simply doing three
#	separate assignments, e.g.:
df['new_col_1'] = np.nan
df['new_col_2'] = 42
df['new_col_3'] = 'wow'

Example 3: assign multiple columns pandas

import pandas as pd

df = {'col_1': [0, 1, 2, 3],
        'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(df)

df[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs',3]  #thought this wo

Example 4: apply a function to multiple columns in pandas

In [49]: df
Out[49]: 
          0         1
0  1.000000  0.000000
1 -0.494375  0.570994
2  1.000000  0.000000
3  1.876360 -0.229738
4  1.000000  0.000000

In [50]: def f(x):    
   ....:  return x[0] + x[1]  
   ....:  

In [51]: df.apply(f, axis=1) #passes a Series object, row-wise
Out[51]: 
0    1.000000
1    0.076619
2    1.000000
3    1.646622
4    1.000000