字典到 Python 中的 DataFrame

问题描述

我从这里检查了许多 questions 但这与我的问题并不完全相同。

让我们创建一个虚拟字典来描述我的问题。

dictionary = {12: {1,2,4,6,8,12,16,65,13,644,653,23},15:{10,20,30,23,56,},17:{4,7,11,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()
,

您可以使用 pd.concatpd.DataFrame.stack

>>> pd.concat([pd.Series(list(val),name=k) for k,val in dictionary.items()],axis=1
              ).stack().reset_index(level=0,drop=True).sort_index()
               .rename_axis('uderId').to_frame('locationid')

        locationid
uderId            
12            65.0
12           653.0
12            13.0
12            12.0
12             8.0
12             6.0
12           644.0
12            16.0
12             4.0
12            23.0
12             2.0
12             1.0
15            56.0
15            23.0
15            30.0
15             8.0
15            10.0
15             6.0
15            20.0
17             7.0
17            19.0
17            11.0
17             4.0
17            12.0
20           234.0
20           545.0
20            54.0
20            40.0
20           123.0
,

您可以使用 12: {1,2,3} 将字典 [(12,1),(12,2),3)] 转换为 itertools.product,然后最终创建数据框

import itertools
data = []
for k,v in dictionary.items():
    data.extend(list(itertools.product([k],v)))

df = pd.DataFrame(data,columns=['userid','locationid'])

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...