0

I have the following DataFrame:

df = pd.DataFrame({
    'From':['a','b','c','d'],
    'To':['h','m','f','f'],
    'week':[1,2,3,3]
})

enter image description here

I want to use column 'To' and 'week' as keys to map to value 'From', create a dictionary like {(1,'h'):'a',(2,'m'):'b',(3,'f'):['c','d']}, is there a way to do this? I tried to use

dict(zip([tuple(x) for x in df[['week','To']].to_numpy()], df['From']))

but it only gives me {(1,'h'):'a',(2,'m'):'b',(3,'f'):'d'}

. If there are multiple 'From's for the same ('week', 'To'), I want to put it in a list or set. Thanks!!

2 Answers 2

1

You can use .groupby() method followed by an .apply(list) method on the column From to convert the results into a list. From here, pandas has a .to_dict() method to convert your results to a dictionary.

>>> df.groupby(['To', 'week'])['From'].apply(list).to_dict()
{('f', 3): ['c', 'd'], ('h', 1): ['a'], ('m', 2): ['b']}
>>>
>>> # use lambda to convert lists with only one value to string
>>> df.groupby(['To', 'week'])['From'].apply(lambda x: list(x) if len(x) > 1 else list(x)[0]).to_dict()
{('f', 3): ['c', 'd'], ('h', 1): 'a', ('m', 2): 'b'}
Sign up to request clarification or add additional context in comments.

Comments

1

Use below code to get your desired dictionary:

df.groupby(['To','week'])['From'].agg(','.join).apply(lambda s: s.split(',') if ',' in s else s).to_dict()

Output:

>>> df.groupby(['To','week'])['From'].agg(','.join).apply(lambda s: s.split(',') if ',' in s else s).to_dict()
{('f', 3): ['c', 'd'], ('h', 1): 'a', ('m', 2): 'b'}

groupby on To,Week and join the values with ,. Then just use apply to convert , separated values into lists, and finally convert the result to dictionary.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.