我有一个NxN数据帧。每一行对应于一个特定的url作为其索引(没有“http://”)。每个also列表示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的传入和传出链接:
^{pr2}$到目前为止还不错。但是,如果我只想计算其他域的传入和传出链接呢?我想我需要按行筛选出列。我尝试了一些类似于转置数据帧(以排除列)和筛选的方法,但失败了:
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())生成第二个数据帧的解决方案,索引到_系列(),轴之间的差异,缺少数据的“False”值-请参见下文);对于中等大小的数据,这种方法可以很好地工作。然而,对于一个大的NxN数据帧(1000x1000),这肯定是一个过度的杀戮。有没有其他方法,也许可以利用就地过滤/映射?在
索引/a列创建对。过滤掉相同域的域并用
False
填充。然后将轴1和加到轴0和上。在不是很喜欢熊猫,但是。。。可以迭代元素
那就
^{pr2}$基准:
更多熊猫方式:
对于1000多个数据帧,第二个解决方案比第一个方案(或piRSquared的方案慢50倍左右)表现出更好的性能。在
相关问题 更多 >
编程相关推荐