7
col1= ['A','B','A','C','A','B','A','C','A','C','A','A','A']
col2= [1,1,4,2,4,5,6,3,1,5,2,1,1]

df = pd.DataFrame({'col1':col1, 'col2':col2})

for A we have [1,4,4,6,1,2,1,1], 8 items but i want to limit the size to 5 while converting Data frame to dict/list

Output:

Dict = {'A':[1,4,4,6,1],'B':[1,5],'C':[2,3,5]}
2
  • How does your original df look like? Commented Aug 20, 2019 at 6:30
  • sorry because of some error i did not put the original df. but now its updated. Commented Aug 20, 2019 at 6:31

2 Answers 2

7

Use pandas.DataFrame.groupby with apply:

df.groupby('col1')['col2'].apply(lambda x:list(x.head(5))).to_dict()

Output:

{'A': [1, 4, 4, 6, 1], 'B': [1, 5], 'C': [2, 3, 5]}
Sign up to request clarification or add additional context in comments.

Comments

4

Use DataFrame.groupby with lambda function, convert to list and filter first 5 values by indexing, last convert to dictionary by Series.to_dict:

d = df.groupby('col1')['col2'].apply(lambda x: x.tolist()[:5]).to_dict()
print (d)
{'A': [1, 4, 4, 6, 1], 'B': [1, 5], 'C': [2, 3, 5]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.