1#Method 1:
2df["Delivery Charges"] = df[["Weight", "Package Size", "Delivery Mode"]].apply(
3 lambda x : calculate_rate(*x), axis=1)
4
5#Method 2:
6df["Delivery Charges"] = df.apply(
7 lambda x : calculate_rate(x["Weight"],
8 x["Package Size"], x["Delivery Mode"]), axis=1)
1# Basic syntax:
2df[['new_column_1_name', 'new_column_2_name']] = pd.DataFrame([[np.nan, 'word']], index=df.index)
3# Where the columns you're adding have to be pandas dataframes
4
5# Example usage:
6# Define example dataframe:
7import pandas as pd
8import numpy as np
9df = pd.DataFrame({
10 'col_1': [0, 1, 2, 3],
11 'col_2': [4, 5, 6, 7]
12})
13
14print(df)
15 col_1 col_2
160 0 4
171 1 5
182 2 6
193 3 7
20
21# Add several columns simultaneously:
22df[['new_col_1', 'new_col_2', 'new_col_3']] = pd.DataFrame([[np.nan, 42, 'wow']], index=df.index)
23print(df)
24 col_1 col_2 new_col_1 new_col_2 new_col_3
250 0 4 NaN 42 wow
261 1 5 NaN 42 wow
272 2 6 NaN 42 wow
283 3 7 NaN 42 wow
29
30# Note, this isn't much more efficient than simply doing three
31# separate assignments, e.g.:
32df['new_col_1'] = np.nan
33df['new_col_2'] = 42
34df['new_col_3'] = 'wow'
1import pandas as pd
2
3df = {'col_1': [0, 1, 2, 3],
4 'col_2': [4, 5, 6, 7]}
5df = pd.DataFrame(df)
6
7df[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs',3] #thought this wo
1In [49]: df
2Out[49]:
3 0 1
40 1.000000 0.000000
51 -0.494375 0.570994
62 1.000000 0.000000
73 1.876360 -0.229738
84 1.000000 0.000000
9
10In [50]: def f(x):
11 ....: return x[0] + x[1]
12 ....:
13
14In [51]: df.apply(f, axis=1) #passes a Series object, row-wise
15Out[51]:
160 1.000000
171 0.076619
182 1.000000
193 1.646622
204 1.000000
21