Pandas row-wise mapper

1.5k views Asked by At

Does Pandas contain an easy method to apply a mapper to each row at at time?

For example:

import pandas as pd
df = pd.DataFrame(
    [[j + (3*i) for j in range(3)] for i in range(4)],
    columns=['a','b','c']
)
print(df)


   a   b   c
0  0   1   2
1  3   4   5
2  6   7   8
3  9  10  11

And then apply some mapper (in pseudocode)

df_ret = df.rowmap(lambda d: d['a'] + d['c'])
print(df_ret)

   0
0  2
1  8
2  14
3  20

Note, adding numbers really isn't the point here. The point is to have a row-wise mapper.

2

There are 2 answers

2
jezrael On BEST ANSWER

You can use apply with parameter axis=1:

df_ret = df.apply(lambda d: d['a'] + d['c'], axis=1)
print(df_ret)
0     2
1     8
2    14
3    20
dtype: int64

but faster is use vectorized solutions:

print (df.a + df.c)
0     2
1     8
2    14
3    20

print (df.a.add(df.c))
0     2
1     8
2    14
3    20
dtype: int64

print (df[['a','c']].sum(axis=1))
0     2
1     8
2    14
3    20
dtype: int64

dtype: int64
0
Asher11 On