我有一个 DataFrame
,df,其 MultiIndex
为 (id1, id2, date)
和一堆列。我有一个 Series
s,它以 (id1, id2)
作为索引,以 date
作为值。我想选择 df 中 (id1, id2, date)
与 s 中相应值匹配的所有行。最好的方法是什么?
我想我可以重置 s
和 df
上的索引,然后使用这些列作为连接列进行右外合并
。这不太好,因为它需要重置散列索引,因此使用它比使用列进行合并更快。似乎不可能有一个没有值的 Series
(并且只有索引为 (id1, id2, date)
),这在这种情况下是理想的。还有其他想法吗?
最佳答案
您可以按 pandas 0.23.0+ 中的列名称和索引合并
:
print (df.merge(s.to_frame(), on=['id1','id2','date']))
示例:
df = pd.DataFrame({'date':pd.date_range('2015-01-01', periods=6),
'id1':[4,5,4,5,5,4],
'id2':[7,8,9,4,2,3],
'F':list('aaabbb')}).set_index(['id1','id2','date'])
print (df)
F
id1 id2 date
4 7 2015-01-01 a
5 8 2015-01-02 a
4 9 2015-01-03 a
5 4 2015-01-04 b
2 2015-01-05 b
4 3 2015-01-06 b
s = pd.DataFrame({'date':pd.date_range('2015-01-01', periods=3),
'id1':[4,5,0],
'id2':[7,8,2]}).set_index(['id1','id2'])['date']
print (s)
id1 id2
4 7 2015-01-01
5 8 2015-01-02
0 2 2015-01-03
Name: date, dtype: datetime64[ns]
df1 = df.merge(s.to_frame(), on=['id1','id2','date'])
print (df1)
date F
id1 id2
4 7 2015-01-01 a
5 8 2015-01-02 a
另一个解决方案:
df1 = df.reset_index().merge(s.reset_index(), on=['id1','id2','date'])
print (df1)
id1 id2 date F
0 4 7 2015-01-01 a
1 5 8 2015-01-02 a
使用reindex
解决方案是可能的,但需要MultiIndex
es的交集:
s_index = s.to_frame().assign(tmp=1).set_index('date', append=True).index
idx = df.index.intersection(s_index)
df1 = df.reindex(idx)
print (df1)
F
id1 id2 date
4 7 2015-01-01 a
5 8 2015-01-02 a
关于python - 根据另一个系列索引从数据框中选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050296/