我有一个数据框 d
,其中包含大约 100,000,000
行和 3
列。它看起来像这样:
import pandas as pd
In [17]: d = pd.DataFrame({'id': ['a', 'b', 'c', 'd', 'e'], 'val': [1, 2, 3, 4, 5], 'n': [34, 22, 95, 86, 44]})
In [18]: d.set_index(['id', 'val'], inplace = True)
我有另一个数据框,其中包含 id
和 val
的值,我想将其保留在 d
中。我想保留大约 600,000 个 id
和 val
的组合:
In [20]: keep = pd.DataFrame({'id':['a', 'b'], 'val' : [1, 2]})
我试过以下方法:
In [21]: keep.set_index(['id', 'val'], inplace = True)
In [22]: d.loc[d.index.isin(keep.index), :]
Out [22]:
n
id val
a 1 34
b 2 22
这行得通,但看起来很笨重,而且速度很慢。这里有更好的方法吗?在 pandas 中切片 Multindex 的最快方法是什么?
最佳答案
使用重新索引
d.reindex(pd.MultiIndex.from_frame(keep))
Out[151]:
n
id val
a 1 34
b 2 22
关于python - pandas:切片 Multiindex 有很多索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56582957/