Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从group by(熊猫)中的多个列创建字典_Python_Pandas_Dataframe_Group By - Fatal编程技术网

Python 从group by(熊猫)中的多个列创建字典

Python 从group by(熊猫)中的多个列创建字典,python,pandas,dataframe,group-by,Python,Pandas,Dataframe,Group By,我的数据框有“id_one”,每个id可以有多个“id_two”。每个id_two还具有许多存储在其他列中的描述性特征。 下面是一个示例数据集 d = {'id_one' : pd.Series([123, 123, 123]), 'id_two' : pd.Series([456, 567, 678]), 'descriptor' : pd.Series(['blue','yellow', 'green'])} df = pd.DataFrame(d) 我需要以每'id

我的数据框有“id_one”,每个id可以有多个“id_two”。每个id_two还具有许多存储在其他列中的描述性特征。 下面是一个示例数据集

d = {'id_one' : pd.Series([123, 123, 123]),
     'id_two' : pd.Series([456, 567, 678]),
     'descriptor' : pd.Series(['blue','yellow', 'green'])}

df = pd.DataFrame(d)
我需要以每'id_one'一行的形式获取数据帧,其中在'col a'中存储'id_one',在'col b'中存储'id_two'的所有值作为字典键,相应的描述符作为字典值存储


非常感谢您的帮助。

这就是您要找的吗

df.groupby('id_one').apply(lambda x: dict(zip(x['id_two'], x['descriptor']))).reset_index().rename(columns={"id_one":"col a", 0:"col b"})
#    col a                                          col b
# 0    123  {456: u'blue', 678: u'green', 567: u'yellow'}

这就是你要找的吗

df.groupby('id_one').apply(lambda x: dict(zip(x['id_two'], x['descriptor']))).reset_index().rename(columns={"id_one":"col a", 0:"col b"})
#    col a                                          col b
# 0    123  {456: u'blue', 678: u'green', 567: u'yellow'}