Rom*_*man 2 python mapper pandas
Pandas 是否包含一种简单的方法来一次将映射器应用于每一行?
例如:
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
Run Code Online (Sandbox Code Playgroud)
然后应用一些映射器(伪代码)
df_ret = df.rowmap(lambda d: d['a'] + d['c'])
print(df_ret)
0
0 2
1 8
2 14
3 20
Run Code Online (Sandbox Code Playgroud)
请注意,添加数字实际上并不是这里的重点。重点是要有一个按行映射器。
您可以apply与参数一起使用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
Run Code Online (Sandbox Code Playgroud)
但更快的是使用矢量化解决方案:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1478 次 |
| 最近记录: |