简体   繁体   中英

Pandas row-wise mapper

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.

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

最快的解决方案: http : //pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html,因为它是内部优化的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM