我正在比较使用map
和apply
来计算Dataframe列的简单乘法的性能
我希望apply
版本会快得多,因为我正在执行向量化numpy函数,而不是一次对一个元素进行操作。
但是,并非如此,两个版本的性能均相同:
应用版本:
import pandas as pd
import numpy as np
np.random.seed(42)
df1 = pd.DataFrame({
'x': np.random.random(size=10000000)
})
df1['2x'] = df1['x'].apply(lambda arr: arr*2)
# CPU times: user 1.64 s, sys: 180 ms, total: 1.82 s
# Wall time: 1.82 s
地图版本:
import pandas as pd
import numpy as np
np.random.seed(42)
df2 = pd.DataFrame({
'x': np.random.random(size=10000000)
})
df2['2x'] = df2['x'].map(lambda element: element *2)
# CPU times: user 1.65 s, sys: 180 ms, total: 1.83 s
# Wall time: 1.83 s
使用的版本:Python 3.6.7,Pandas 0.24.2,Numpy 1.16.3
为什么apply
版本使用的是numpy向量化函数,所以它为什么没有比map
版本快得多?
答案 0 :(得分:3)
int main() {
std::ifstream reading_file;
reading_file.open("smalldata-n.txt", std::ios::in);
std::string line;
std::getline(reading_file, line);
std::cout << "1. first line is: " << line << std::endl;
return 0;
}
只是伪装的for循环,不是矢量化。您已经通过调用lambda元素apply()
来自欺欺人,但这实际上是一个标量。
相反,请保持简单,这相当于快100倍:
arr