pandas 从 B 系列中获取也在 A 系列中的条目;但仅在系列 A 中唯一的条目应具有 0 的填充值
pandas get entries from Series B that are also in Series A; but entries unique only in Series A shall have a fill value of 0
这是一种独特的join/combine,但我不知道这叫什么,所以请随时用术语纠正我。
所以例如我有一个系列 profile
如下:
In [1]: profile = pd.Series(data=[0.8,0.64,0.51,0.5,0.5], index=['google.com','facebook.com','twitter.com', 'instagram.com', 'github.com'])
In [2]: profile
Out[2]:
google.com 0.80
facebook.com 0.64
twitter.com 0.51
instagram.com 0.50
github.com 0.50
dtype: float6
我有一个 transaction
系列如下:
In [3]: transaction = pd.Series(data=[1,1,1,1], index=['twitter.com','facebook.com','instagram.com','9gag.com'])
In [4]: transaction
Out[4]:
twitter.com 1
facebook.com 1
instagram.com 1
9gag.com 1
dtype: int64
我想要实现的是一个系列 window
,我在其中比较 profile
和 transaction
:如果 transaction
中的索引也存在于 profile
,我们得到那个特定的索引和它各自的值。仅在 profile
中唯一的其余索引应具有填充值 0.
In [5]: window
Out[5]:
google.com 0
facebook.com 1
twitter.com 1
instagram.com 1
github.com 0
dtype: int64
是否有任何现有的内置 methods/functions 可以做到这一点?
我试验过:
window = transaction[transaction.keys().isin(profile.keys())]
但它只是 returns transaction
和 profile
的交集。
我在 Series
中发现了这个 combine()
函数,但我不知道在 func
参数中应用什么(isin()
无效)。
从 Pandas 的 v.0.17.0 开始,您可以重新索引系列。
>>> transaction.reindex(profile.index).fillna(0)
google.com 0
facebook.com 1
twitter.com 1
instagram.com 1
github.com 0
dtype: float64
它似乎也比使用 loc
稍微快一些,尽管我没有在更大的数据帧上测试过它。
%timeit transaction.reindex(profile.index).fillna(0)
1000 loops, best of 3: 224 µs per loop
%timeit transaction.loc[profile.index].fillna(0)
1000 loops, best of 3: 329 µs per loop
这是一种独特的join/combine,但我不知道这叫什么,所以请随时用术语纠正我。
所以例如我有一个系列 profile
如下:
In [1]: profile = pd.Series(data=[0.8,0.64,0.51,0.5,0.5], index=['google.com','facebook.com','twitter.com', 'instagram.com', 'github.com'])
In [2]: profile
Out[2]:
google.com 0.80
facebook.com 0.64
twitter.com 0.51
instagram.com 0.50
github.com 0.50
dtype: float6
我有一个 transaction
系列如下:
In [3]: transaction = pd.Series(data=[1,1,1,1], index=['twitter.com','facebook.com','instagram.com','9gag.com'])
In [4]: transaction
Out[4]:
twitter.com 1
facebook.com 1
instagram.com 1
9gag.com 1
dtype: int64
我想要实现的是一个系列 window
,我在其中比较 profile
和 transaction
:如果 transaction
中的索引也存在于 profile
,我们得到那个特定的索引和它各自的值。仅在 profile
中唯一的其余索引应具有填充值 0.
In [5]: window
Out[5]:
google.com 0
facebook.com 1
twitter.com 1
instagram.com 1
github.com 0
dtype: int64
是否有任何现有的内置 methods/functions 可以做到这一点?
我试验过:
window = transaction[transaction.keys().isin(profile.keys())]
但它只是 returns transaction
和 profile
的交集。
我在 Series
中发现了这个 combine()
函数,但我不知道在 func
参数中应用什么(isin()
无效)。
从 Pandas 的 v.0.17.0 开始,您可以重新索引系列。
>>> transaction.reindex(profile.index).fillna(0)
google.com 0
facebook.com 1
twitter.com 1
instagram.com 1
github.com 0
dtype: float64
它似乎也比使用 loc
稍微快一些,尽管我没有在更大的数据帧上测试过它。
%timeit transaction.reindex(profile.index).fillna(0)
1000 loops, best of 3: 224 µs per loop
%timeit transaction.loc[profile.index].fillna(0)
1000 loops, best of 3: 329 µs per loop