python - 内存数据帧的昂贵计算

标签 python pandas memoization

我有一个昂贵的计算,在 pandas DataFrames 上运行。我想记住它。我想弄清楚,我可以为此使用什么。

In [16]: id(pd.DataFrame({1: [1,2,3]}))
Out[16]: 52015696

In [17]: id(pd.DataFrame({1: [1,2,3]}))
Out[17]: 52015504

In [18]: id(pd.DataFrame({1: [1,2,3]}))
Out[18]: 52015504

In [19]: id(pd.DataFrame({1: [1,2,3]})) # different results, won't work for my case
Out[19]: 52015440

In [20]: hash(pd.DataFrame({1: [1,2,3]})) # throws
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-3bddc0b20163> in <module>()
----> 1 hash(pd.DataFrame({1: [1,2,3]}))

/usr/local/lib/python2.7/dist-packages/pandas/core/generic.pyc in __hash__(self)
     52     def __hash__(self):
     53         raise TypeError('{0!r} objects are mutable, thus they cannot be'
---> 54                               ' hashed'.format(self.__class__.__name__))
     55 
     56     def __unicode__(self):

TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed

是否可以做我想做的事,因为我确定我不会改变被记忆化的 DataFrame

最佳答案

如果您不介意比较索引或列名,您可以将 DataFrame 转换为元组:

>>> df1 = pd.DataFrame({1: [1,2,3]})
>>> df2 = pd.DataFrame({1: [1,2,3]})
>>> hash(tuple(tuple(x) for x in df1.values)) == hash(tuple(tuple(x) for x in df2.values))
True
>>> id(df1) == id(df2)
False

你也可以使用 map 函数代替生成器:

tuple(map(tuple, df1.values))

如果你也需要比较索引,你可以将它添加为一个列。您还可以通过创建 namedtuple 来保留列名:

>>> from collections import namedtuple
>>> from pprint import pprint
>>> df = pd.DataFrame({1: [1,2,3], 2:[3,4,5]})
>>> df['index'] = df.index
>>> df
   1  2  index
0  1  3      0
1  2  4      1
2  3  5      2
>>>
>>> dfr = namedtuple('row', map(lambda x: 'col_' + str(x), df.columns))
>>> res = tuple(map(lambda x: dfr(*x), df.values))
>>> pprint(res)
(row(col_1=1, col_2=3, col_index=0),
 row(col_1=2, col_2=4, col_index=1),
 row(col_1=3, col_2=5, col_index=2))

希望对您有所帮助。

关于python - 内存数据帧的昂贵计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19786040/

相关文章:

python - 将内存装饰器缓存转储到文件

python - 使用正则表达式删除重复的字符?

python - 将 pandas 输出格式化为 csv

python - 将项目添加到 pandas.Series?

javascript - 为什么这个内存实现对匿名函数有效,但对声明的函数无效?

ruby - 避免使用 Enumerable 方法重新计算某些值

python - re.findall 和 re.finditer 的区别——Python 2.7 re 模块中的 bug?

Python 多处理(joblib)参数传递的最佳方式

python - 类型错误 : 'list' object is not callable while trying to access a list

python - 使用 Pandas 从复杂的字典/列表中创建 DataFrame