df multiple columns code example
Example 1: 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 2: 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]
Example 3: 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)
Out[51]:
0 1.000000
1 0.076619
2 1.000000
3 1.646622
4 1.000000