Skip to main content
 首页 » 编程设计

python之根据行索引值对 Pandas 数据框列的值求和

2024年10月17日7小虾米

我有一个 NxN 数据框。每行对应于作为其索引给出的特定 url(不带“http://”)。每个列也代表带有 bool 值的 url,指示此页面(行索引)是否链接到该页面(列名)。索引和列中的 url 相同。

In [1]: import pandas as pd 
 
In [2]: from pandas import DataFrame 
 
In [3]:  df = DataFrame({'domain1.com/url1':[True,False,False,True,False],'domain2.com/url2':[False,True,False,True,True],'domain1.com/url3':[False,False,False,True,False],'domain3.com/url4':[False,True,False,True,False],'domain2.com/url5':[False,True,False,True,True]}, index=['domain1.com/url1','domain2.com/url2','domain1.com/url3','domain3.com/url4','domain2.com/url5']) 
 
In [4]: df 
Out[4]:  
                 domain1.com/url1 domain1.com/url3 domain2.com/url2  \ 
domain1.com/url1             True            False            False    
domain2.com/url2            False            False             True    
domain1.com/url3            False            False            False    
domain3.com/url4             True             True             True    
domain2.com/url5            False            False             True    
 
                 domain2.com/url5 domain3.com/url4   
domain1.com/url1            False            False   
domain2.com/url2             True             True   
domain1.com/url3            False            False   
domain3.com/url4             True             True   
domain2.com/url5             True            False   

例如,现在我可以计算每个 url 的传入和传出链接:

In [5]: in_links_count = df.sum(axis=0) 
 
In [6]: in_links_count 
Out[6]:  
domain1.com/url1    2 
domain1.com/url3    1 
domain2.com/url2    3 
domain2.com/url5    3 
domain3.com/url4    2 
dtype: int64 
 
In [7]: out_links_count = df.sum(axis=1) 
 
In [8]: out_links_count 
Out[8]:  
domain1.com/url1    1 
domain2.com/url2    3 
domain1.com/url3    0 
domain3.com/url4    5 
domain2.com/url5    2 
dtype: int64 

到目前为止一切顺利。但是,如果我只想计算其他 域的传入和传出链接怎么办?我想我需要以某种方式按行过滤掉列。我尝试了转置数据框(以排除列)和过滤之类的方法,但失败了:

In [9]: df_t = df.T 
 
In [10]: df_t[ filter(lambda x: x.split('/')[0] != df_t.index.map(lambda x: x.split('/')[0]), list(df_t)) ].sum(axis=0) 
--------------------------------------------------------------------------- 
ValueError                                Traceback (most recent call last) 
<ipython-input-10-279439127551> in <module>() 
----> 1 df_t[ filter(lambda x: x.split('/')[0] != df_t.index.map(lambda x: x.split('/')[0]), list(df_t)) ].sum(axis=0) 
 
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

有什么想法吗,伙计们?

更新:

@piRSquared 提供了一种解决方案,它通过分层索引生成第二个数据帧(stack()、index.to_series()、轴之间的差异、缺失数据的“假”值 - 见下文);这适用于中等大小的数据。然而,对于一个大的 NxN 数据帧 (1000x1000),这肯定是一种矫枉过正。是否可以有另一种方式,或许利用就地过滤/映射?

请您参考如下方法:

不是很 Pandas ,但仍然......可以迭代元素

In [40]: def same_domain(url1, url2): 
    return url1.split('/')[0] == url2.split('/')[0] 
 
 
In [41]: def clear_inner_links(df): 
for r in df.index: 
    for c in df.columns: 
        if(same_domain(r,c)): 
            df.loc[r,c] = False 
return df 

然后就

df1.sum(0) 
df1.sum(1) 

基准:

In [35]: new_df.shape 
Out[35]: (500, 500) 
 
In [36]: %timeit clear_inner_links(new_df) 
1 loop, best of 3: 956 ms per loop 

更多 Pandas 方式:

In [102]: def same_domain(url1, url2): 
   .....:         return url1.split('/')[0] == url2.split('/')[0] 
   .....:  
 
In [103]: def apply_criterion(s): 
   .....:         s[s.index.map(lambda x: same_domain(x,s.name))] = False 
   .....:      
 
In [104]: def clear_inner_links2(df): 
   .....:         df.apply(apply_criterion, axis=0) 
   .....:         return df 
   .....:  
 
In [105]: new_df.shape 
Out[105]: (500, 500) 
 
In [106]: %timeit clear_inner_links2(new_df) 
1 loop, best of 3: 929 ms per loop 

对于 1000 多个数据帧,第二个解决方案比第一个解决方案(或 piRSquared 的慢约 50 倍)表现出更好的性能。