字典到Python中的DataFrame
我从这里检查了很多问题,但这与我的问题并不完全相同。
让我们创建一个虚拟字典来描述我的问题。
dictionary = {12: {1,2,4,6,8,12,16,65,13,644,653,23}, 15:{10,20,30,23,56,6,8,}, 17:{4,7,11,12,19}, 20:{40,54,123,545,234}}
这里的键是 userid,值是 location-id。
我的目标是创建一个这样的数据框
userid locationid
12 1
12 2
12 4
... ...
15 20
15 30
15 23
... ...
17 4
17 7
17 11
... ...
20 40
20 54
... ...
我的解决方案
for dictkey in range(len(dictionary.keys())):
lids = list(np.array(list(dictionary.values())[dictkey]).item())
userid = np.array(list(dictionary.keys())[dictkey])
userid = userid.reshape(1,1)
df= pd.DataFrame(userid, columns =['userid'])
df['locationid'] = lids
但它不起作用。我应该如何处理这个问题?我无法解决
注意:通常我的真实数据集很大。
回答
您可以转换为系列然后爆炸:
pd.Series(dictionary).map(list).explode()
12 1
12 2
12 65
12 4
12 644
12 6
12 8
12 12
12 13
12 653
12 16
12 23
15 6
15 8
15 10
15 20
15 23
15 56
15 30
17 4
17 7
17 11
17 12
17 19
20 545
20 40
20 234
20 54
20 123
dtype: object
或者对于更高版本的pandas >= 1.2.0,也可以使用(感谢@ aneroid)
pd.Series(dictionary).explode()
- @aneroid thank you for your research 🙂 do you mind if I add your suggestion in the solution?