问题
I have these two series:
In [48]: serie1
Out[48]:
0 A
1 B
2 C
3 A
4 D
In [49]: serie2
Out[49]:
0 X
1 Y
2 A
3 Z
4 A
5 D
dtype: object
And for each value in serie1 I want to get the index/indexes from serie2. Is this possible without iterating over values? A possible solution would be to build a dataframe more or less like this:
A B C D
X False False False False
Y False False False False
A True False False False
Z False False False False
A True False False False
D False False False True
... and then get the index of the "True" values for each column
回答1:
I think serie2.index[(array(serie2)=='A').flatten()]
may work. 'A'
is the value you want to find index for.
Or this, which may be less readable: serie2.index[(serie2=='A')[0]]
回答2:
1) For the boolean table of matches: if you want a crosstabulation (only shows unique values, no repetitions), and then convert it to boolean:
serie1 = pd.Series(['A','B','C','A','D'])
serie2 = pd.Series(['X','Y','A','Z','A','D'])
pd.crosstab(serie2,serie1) > 0
col_0 A B C D
row_0
A False False True True
X True False False False
Y False True False False
Z True False False False
(Note that the row-index is automatically sorted by value, so not the order in which the values appear in serie1
. You may be able to override that by playing with .reorder_levels(...)
)
2) As for the indices of matches, to get them as a dict of arrays...
serie2.groupby(serie1).indices
{'A': array([0, 3]), 'C': array([2]), 'B': array([1]), 'D': array([4])}
# ... or as a list of arrays...
serie2.groupby(serie1).indices.values()
[array([0, 3]), array([2]), array([1]), array([4])]
# Here are alternatives with list comprehensions which are probably less efficient than `Series.groupby()`
>>> [ np.flatnonzero(serie2.apply(lambda i2: i2==i1)) for i1 in serie1 ]
[array([2, 4]), array([], dtype=int64), array([], dtype=int64), array([2, 4]), array([5])]
>>> [ np.flatnonzero(serie2.apply(lambda i2: i2==i1)).tolist() for i1 in serie1 ]
[[2, 4], [], [], [2, 4], [5]]
来源:https://stackoverflow.com/questions/21665162/python-pandas-how-to-get-the-index-of-the-values-from-a-series-that-have-match