0
說我有以下幾大系列,dtype('O')
:地圖熊貓系列列出會員
s = pd.Series(list('abcde'))
而下面的列表(組):
group1 = list('ab')
group2 = list('cd')
group3 = list('xy')
我要地圖s
到一個新的系列根據組成員資格,在沒有成員資格的情況下填寫np.nan
。結果:
res
Out[17]:
0 group1
1 group1
2 group2
3 group2
4 nan
dtype: object
我在尋找這樣做不是使用np.where
重複一個更Python的方式:
res = pd.Series(np.where(s.isin(group1), 'group1',
np.where(s.isin(group2), 'group2',
np.where(s.isin(group3), 'group3',
np.nan))))
理想的情況下,這將意味着做這樣的事情,指定列表的集合作爲一個單一可迭代的,因爲在我真正的問題中,我有更多的組。 res
可以是dtype O
或categorical
。
我已經試過什麼:
- 上面的例子有
np.where
,這工作,但過於冗長。 - 創建
dict(zip(['group1', 'group2', 'group3'], [group1, group2, group3]))
。卡在那裏。
我有一種感覺,這可能是重複的,但我第一次嘗試時無法找到。
注意:組列表將永遠是不相交的。
我之前沒有機會回覆您的評論。我認爲你最好的選擇是在開始時構建映射,但我不知道你是如何得到這些列表的。無論如何,如果效率是一個問題,請不要接受。如果問題沒有結束,人們更有可能從事替代方案。 – ayhan