Skip to main content
 首页 » 编程设计

python之Pandas 索引摘要

2025年04月02日8zhwl

我想高效计算 Pandas DataFrame 的摘要,该摘要可以唯一且可重复地标识其内容(用于版本控制目的)。现在假设我不担心字节顺序、数据类型、索引类型或列。还假设索引和列都已经排序为 monotonic_increasing。

事情与值相当顺利(同样,为了简化,假设 np.float64)。但是我在索引(和列)方面遇到了麻烦,并且没有得到一致的摘要。当然我可以做一些事情,比如将索引转换成字符串,然后是 utf-8 字节,但那很慢。

这是一个简化的例子:

import hashlib 
def pd_val_sha1(df): 
    x = df.values 
    if not x.flags.c_contiguous: 
        x = x.copy(order='C') 
    return hashlib.sha1(x).hexdigest() 

测试:

import pandas as pd 
import io 
 
str = """s,e,id,x,y,z 
2012-01-01,2013-01-01,b,NaN,2,3 
2015-10-27,2015-11-03,a,0.04,12.7,NaN 
2015-11-15,2016-01-01,a,7.3,-1.2,8 
""" 
df = pd.read_csv(io.StringIO(str), parse_dates=[0,1], index_col=[0,1,2]).sort_index() 
df 

输出:

                            x     y    z 
s          e          id                  
2012-01-01 2013-01-01 b    NaN   2.0  3.0 
2015-10-27 2015-11-03 a   0.04  12.7  NaN 
2015-11-15 2016-01-01 a   7.30  -1.2  8.0 

值的 SHA-1:

pd_val_sha1(df) 
>>> 'a7f0335988a967606bd030864e0e30ce03f32ec9' 
 
pd_val_sha1(df.head()) 
>>> 'a7f0335988a967606bd030864e0e30ce03f32ec9' 
 
pd_val_sha1(pd.concat([df.ix[0:2], df.ix[2:3]])) 
>>> 'a7f0335988a967606bd030864e0e30ce03f32ec9' 

到目前为止,还不错。但是当谈到索引时:

pd_val_sha1(df.index) 
>>> inconsistent value (re-run the example from read_csv and we'll get 
... a different result). 

我尝试了其他各种方法,例如使用 index.data 或 index.to_native_types() 或 np.array(index.tolist()) 而不是 index.values ,但我仍然得到不一致的结果,因为我认为基础数据可能会有所不同。

到目前为止似乎有效的一件事是 hashlib.sha1(np.array(df.index.format())).hexdigest()。但它很慢,例如(5000000,12) 数据帧 2 分钟 34 秒,而内容本身在 900 毫秒内完成指纹识别。

有什么建议吗?

请您参考如下方法:

有时解决方案就在我们眼皮底下...

from sklearn.externals import joblib 
 
%%time 
joblib.hash(df, hash_name='sha1') 
>>> consistent value that depends on values and axes 
Wall time: 1.66 s  (for the (5000000,12) DataFrame mentioned above)