现在有一个 dataframe, 其中的几列需要单独处理
方案 1 是:
df['foo1'] = df['foo1'].apply(lambda x: func1(x)) df['foo2'] = df['foo2'].apply(lambda x: func2(x)) df['foo3'] = df['foo3'].apply(lambda x: func3(x)) ...
方案 2 是:
def pipeline(ser): ser = (ser.pipe(func1) .pipe(func2) .pipe(func3)) df = df.apply(lambda x: pipeline(x), axis=1)
在我感觉上是方案 2
应该是比方案 1
要快的,但是实际运行下来发现方案 2
时间更长...
难道是我理解错了吗,按列处理会更快,即使是使用了 apply
1 cyberpoint 2022-09-28 16:24:55 +08:00 不理解 |
2 Renormalization 2022-09-28 16:47:16 +08:00 ![]() pandas 按列处理肯定是最快的。<<Python for Finance>>书上的原话是"Working with the columns (Series objects) directly is the fastest approach"。另一句是"The slowest option is to use the apply() method row-by-row; this is like looping on the Python level over all rows". |
![]() | 3 ipwx 2022-09-28 16:49:12 +08:00/span> ![]() Pandas 是按列存储的。 |
![]() | 4 LuJason OP ![]() @Renormalization 是的 我已经试验出来了,一开始以为 apply 的少的会快一些 |