Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

pandas - Convert Dictionary Values into Array in Python

I know this question is simple but I couldn't get it.

I have a dataframe which is called df_check like the one below

enter image description here

I created a dictionary using the code block below

userdic = df_check.groupby('userid')['poiid'].agg(set).to_dict()

userdict output looks like below

print(userdic)

{1337: {9943, 9996, 10202, 10616}, 1339: {10202, 10725,
11601}, 5: {9177, 9489, 10190, 10349}, 54: {123, 4, ...

My goal is to get the values of each key but I have to take them as arrays because I will be working in for loop.

My Solution to get the first key's values.

dict2list = list(userdic.values())[0]
list2array= np.array(dict2list ) 

When I print list2array, I get the result as below.

enter image description here

My expectation like this

[360448, 486401, 190984, 941599, ... ]

but output like this

array({360448, 486401, 190984, 941599, ...},dtype=object)

question from:https://stackoverflow.com/questions/65872114/convert-dictionary-values-into-array-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you aggregated into a set, your numpy array isn't actually an array. To get the list back you can do list(list2array.item()) and index on that

If you change your list(userdic.values())[0] to list(userdic.values()[0]), your initial list will actually be a list instead of a set and the array will get initiated properly


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...