pandas change multiple column types code example

Example 1: pandas change multiple column types

#Method 1:
df["Delivery Charges"] = df[["Weight", "Package Size", "Delivery Mode"]].apply(
  lambda x : calculate_rate(*x), axis=1)

#Method 2:
df["Delivery Charges"] = df.apply(
  lambda x : calculate_rate(x["Weight"], 
  x["Package Size"], x["Delivery Mode"]), axis=1)

Example 2: set dtype for multiple columns pandas

import pandas as pd

df = pd.DataFrame({'id':['a1', 'a2', 'a3', 'a4'],
  				   'A':['0', '1', '2', '3'],
                   'B':['1', '1', '1', '1'],
                   'C':['0', '1', '1', '0']})

df[['A', 'B', 'C']] = df[['A', 'B', 'C']].apply(pd.to_numeric, axis = 1)

Example 3: pandas change multiple column types

#Two ways to do this
df[['parks', 'playgrounds', 'sports']].apply(lambda x: x.astype('category'))

cols = ['parks', 'playgrounds', 'sports', 'roading']:
public[cols] = public[cols].astype('category')