python - 将 groupby 选定的列作为字典移动到新的 pandas 列中

标签 python pandas dataframe dictionary

我在 python 中有以下 pandas DataFrame:

df = pd.DataFrame({'id': [1, 1, 2, 2, 3],
                   'field1': [1, 2, 3, 4, 5],
                   'field2': ['a', 'b', 'c', 'd', 'e']})
    id  field1  field2
0   1   1       a
1   1   2       b
2   2   3       c
3   2   4       d
4   3   5       e

我想按 id 对上表进行分组,然后将该组中所有选定的列值移动到一个新列中作为 python 字典列表。

所以从上面我想制作这个:

    id  fields
0   1   [{'field1': 1, 'field2': 'a'}, {'field1': 2, 'field2': 'b'}]
2   2   [{'field1': 3, 'field2': 'c'}, {'field1': 4, 'field2': 'd'}]
4   3   [{'field1': 5, 'field2': 'e'}]

我可以使用以下 python 代码实现此目的:

def test(df):
    df['fields'] = [df[['field1', 'field2']].to_dict(orient='records')]*len(df)
    return df

df.groupby('id').apply(test).drop_duplicates('id')[['id', 'fields']]

但我相信它可以做得更好。问题是如何? 我对这部分特别不满意:

df['fields'] = [df[['field1', 'field2']].to_dict(orient='records')]*len(df)

我必须制作一个包含组长度的列表,以便为行分配相同的字典值。 此外,这使它更需要内存。

最佳答案

也许

df.set_index('id').groupby(level=0).apply(pd.DataFrame.to_dict, orient='r')

id
1    [{'field1': 1, 'field2': 'a'}, {'field1': 2, 'field2': 'b'}]
2    [{'field1': 3, 'field2': 'c'}, {'field1': 4, 'field2': 'd'}]
3    [{'field1': 5, 'field2': 'e'}]
dtype: object

总是可以在末尾添加 .to_frame('fields') 以获得 df

关于python - 将 groupby 选定的列作为字典移动到新的 pandas 列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58306885/

相关文章:

python - 通过日期时间索引中的间隙分块 DataFrame

python - 将数据框转换为包含字典列表的字典

python - 匹配 python 正则表达式中的复杂表达式

python - URLlib 未显示在谷歌分析中

python - 如何正确设置 json 文件中的重复字段

python - Pandas:编写带有 Windows 行结尾的 CSV 文件

python - 如何将字典转换为数据框,并将值作为标题和行?

python - 使用Python从列表中删除标点符号/符号(句点、逗号除外)

python - 基于现有单元格填充单元格

python - 当列名是整数时合并列