【发布时间】:2017-09-23 10:11:51
【问题描述】:
在写入pandas 中的数据框时,我们看到this answer 和this answer 提供了几种方法。
我们有方法
-
df[r][c].set_value(r,c,some_value)和 的方法
-
df.iloc[r][c] = some_value。
有什么区别?哪个更快?是副本吗?
【问题讨论】:
-
根据您自己发布的答案,这似乎是速度问题。
在写入pandas 中的数据框时,我们看到this answer 和this answer 提供了几种方法。
我们有方法
df[r][c].set_value(r,c,some_value)和df.iloc[r][c] = some_value。 有什么区别?哪个更快?是副本吗?
【问题讨论】:
区别在于set_value是返回一个对象,而赋值运算符将值赋给现有的DataFrame对象。
在调用set_value 之后,您可能会有两个 DataFrame 对象(这并不一定意味着您将拥有两个数据副本,因为DataFrame 对象可以“引用”一个另一个)而赋值运算符将更改单个 DataFrame 对象中的数据。
使用set_value 似乎更快,因为它可能针对该用例进行了优化,而分配方法将生成数据的中间切片:
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: df=pd.DataFrame(np.random.rand(100,100))
In [4]: %timeit df[10][10]=7
The slowest run took 6.43 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 89.5 µs per loop
In [5]: %timeit df.set_value(10,10,11)
The slowest run took 10.89 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 3.94 µs per loop
set_value 的结果可能是一个副本,但documentation 对此并不十分清楚(对我而言):
返回:
帧:数据帧
如果包含标签对,则引用调用DataFrame,否则为新对象
【讨论】: