簡體   English   中英

當鍵的值是列表列表時,如何將字典轉換為 dataframe?

[英]How to convert dictionary to dataframe when values of keys are list of list?

我有 dataframe 看起來像這樣..

{'abc2035': [['abc3007', 2],['abc2006', 2],['abc2003', 1],['abc3000', 3]],
 'abc2001': [['abc3002', 1],['abc2096', 2],['abc2003', 2],['abc3009', 3],['abc2015',3]],
 'abc2052': [['abc1003', 2],['abc2090', 2]],
.
.
.}

我想將它轉換為像這樣的 dataframe ..

userID    with_common   no_of_common
abc2035    abc3007       2
abc2035    abc2006       2
abc2035    abc2003       1
abc2035    abc3000       3
abc2001    abc3002       1
abc2001    abc2096       2
abc2001    abc2003       2
abc2001    abc3009       3
abc2001    abc2015       3
.
.
.

對此有什么幫助嗎?

利用:

cols = ['userID',' with_common','no_of_common']
df = pd.DataFrame([(k, *x) for k, v in d.items() for x in v], columns=cols)
print (df)
     userID  with_common  no_of_common
0   abc2035      abc3007             2
1   abc2035      abc2006             2
2   abc2035      abc2003             1
3   abc2035      abc3000             3
4   abc2001      abc3002             1
5   abc2001      abc2096             2
6   abc2001      abc2003             2
7   abc2001      abc3009             3
8   abc2001      abc2015             3
9   abc2052      abc1003             2
10  abc2052      abc2090             2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM