我有一个如下所示的DataFrame:
Market | Status | Team | Member |
-------|--------|------|--------|
Chicago| 1 | ENG | None |
Chicago| 1 | ENG | None |
SF Bay | 3 | ENG | Julia |
用户及其电子邮件的字典:
TeamMembers = {
"Julia": "julia@email.com", "Tyler": "tyler@email.com", "Kyle": "kyle@email.com"
}
在我的DataFrame中,如果没有成员,我想随机分配一个成员,但如果市场价值相同,那么成员也需要相同。
我想用
name, email = random.choice(list(TeamMembers.items()))
获取具体的姓名和电子邮件地址,但我不确定如何根据市场相同的值来操纵DataFrame。
答案 0 :(得分:4)
您可以将transform
与fillna
一起使用,也可以通过将name
更改为item
来生成key
:
df['Member'] = (df.groupby('Market')['Member']
.transform(lambda x: x.fillna(random.choice(list(TeamMembers.keys())))))
print (df)
Market Status Team Member
0 Chicago 1 ENG Kyle
1 Chicago 1 ENG Kyle
2 SF Bay 3 ENG Julia
答案 1 :(得分:2)
这是另一种解决方案。这个的好处是,如果芝加哥已被映射到一个成员,其他实例将被映射到同一成员,即使当前None
。
import pandas as pd
import random
df = pd.DataFrame([['Chicago', 1, 'ENG', None],
['Chicago', 1, 'ENG', None],
['SF Bay', 3, 'ENG', 'Julia'],
['SF Bay', 2, 'ENG', None],
['NY', 1, 'ENG', None],
['NY', 2, 'ENG', None]],
columns=['Market', 'Status', 'Team', 'Member'])
TeamMembers = {"Julia": "julia@email.com", "Tyler": "tyler@email.com", "Kyle": "kyle@email.com"}
existing_map = df.dropna(subset=['Member']).set_index('Market')['Member'].to_dict()
unmapped = list(set(df.loc[pd.isnull(df['Member']), 'Market']) - set(existing_map))
MemberChoices = list(TeamMembers.keys())
random.shuffle(unmapped)
random.shuffle(MemberChoices)
additional_map = {k: MemberChoices[i % len(MemberChoices)] for i, k in enumerate(unmapped)}
new_map = {**existing_map, **additional_map}
df['Member'] = df['Member'].fillna(df['Market'].map(new_map))
# Market Status Team Member
# 0 Chicago 1 ENG Tyler
# 1 Chicago 1 ENG Tyler
# 2 SF Bay 3 ENG Julia
# 3 SF Bay 2 ENG Julia
# 4 NY 1 ENG Kyle
# 5 NY 2 ENG Kyle
答案 2 :(得分:0)
没有groupby
k=df.Market.unique().tolist()
list(TeamMembers.keys())
Out[31]: ['Julia', 'Tyler', 'Kyle']
d=dict(zip(k,random.sample(set(list(TeamMembers.keys())), 2)))
df.Member=df.Member.fillna(df.Market.map(d))