Python| Pandas Index.intersection()
Python是一种用于进行数据分析的出色语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas就是其中之一,它使导入和分析数据变得更加容易。
Pandas Index.intersection()
函数形成两个索引对象的交集。这将返回一个新索引,其中包含索引和其他共有的元素,并保留调用索引的顺序。
Syntax: Index.intersection(other)
Parameters :
other : Index or array-like
Returns : intersection : Index
示例 #1:使用Index.intersection()
函数查找两个索引的集合交集。
# importing pandas as pd
import pandas as pd
# Creating the first Index
idx1 = pd.Index(['Labrador', 'Beagle', 'Mastiff',
'Lhasa', 'Husky', 'Beagle'])
# Creating the second Index
idx2 = pd.Index(['Labrador', 'Great_Dane', 'Pug',
'German_sepherd', 'Husky', 'Pitbull'])
# Print the first and second Index
print(idx1, '\n', idx2)
输出 :
现在我们找到两个索引的集合交集。
# Find the elements common to both the Indexes
idx2.intersection(idx1)
输出 :
正如我们在输出中看到的, Index.intersection()
函数返回了两个索引的交集。标签的顺序已根据调用索引进行维护。示例 #2:使用Index.intersection()
函数查找两个索引的集合交集。索引包含NaN
值。
# importing pandas as pd
import pandas as pd
# Creating the first Index
idx1 = pd.Index(['2015-10-31', '2015-12-02', None, '2016-01-03',
'2016-02-08', '2017-05-05', '2014-02-11'])
# Creating the second Index
idx2 = pd.Index(['2015-10-31', '2015-10-02', '2018-01-03',
'2016-02-08', '2017-06-05', '2014-07-11', None])
# Print the first and second Index
print(idx1, '\n', idx2)
输出 :
现在我们找到 idx1 和 idx2 的交集。
# find intersection and maintain
# ordering of labels based on idx1
idx1.intersection(idx2)
输出 :
注意:两个索引中的缺失值被认为是共同的。