如何将一组pandas dataframe列转换为字典列表并将其保存到新列中?

qyzbxkaa  于 2023-03-21  发布在  其他
关注(0)|答案(2)|浏览(141)

我有一个dataframe

col1 col2 col3
0     1    a    W
1     1    b    X
2     2    c    Y
3     2    d    Z

我需要将它转换成这样的东西,根据第1列的值进行组合:

col1 col2 col3                    dict_col
0     1    a    W  [{'col2': 'a', 'col3': 'W'}, {'col2': 'b', 'col3': 'X'}]
0     2    c    Y  [{'col2': 'c', 'col3': 'Y'}, {'col2': 'd', 'col3': 'Z'}]

这是我尝试做的:

import pandas as pd

data = {
    'col1': [1, 1, 2, 2],
    'col2': ['a', 'b', 'c', 'd'],
    'col3': ['W', 'X', 'Y', 'Z']}
df = pd.DataFrame(data)

print(df)

cols_to_use = ['col2','col3']

df['dict_col'] = df[cols_to_use].apply(
    lambda x: {'col2': x['col2'], 'col3': x['col3']},
    axis=1)

print(df)
4ioopgfo

4ioopgfo1#

您可以用途:

g = df.groupby('col1')

df1 = g.apply(lambda x: x.drop(columns='col1').to_dict('records')).rename('dict_col')
out = pd.concat([g.first(), df1], axis=1).reset_index()

您还可以选择:

g = df.drop(columns='col1').groupby(df['col1'])

df1 = g.apply(lambda x: x.to_dict('records')).rename('dict_col')
out = pd.concat([g.first(), df1], axis=1).reset_index()

输出:

>>> out
   col1 col2 col3                                           dict_col
0     1    a    W  [{'col2': 'a', 'col3': 'W'}, {'col2': 'b', 'co...
1     2    c    Y  [{'col2': 'c', 'col3': 'Y'}, {'col2': 'd', 'co...
tez616oj

tez616oj2#

您可以使用groupby,然后应用您的函数:

def group_rows(sub_df):
    dict_col = []
    for i, row in sub_df.iterrows():
        dict_col.append(dict(row))
    return pd.Series({
            "col2": dict_col[0]["col2"],
            "col3": dict_col[0]["col3"],
            "dict_col": dict_col
            })
df.groupby("col1").apply(group_rows)

这会给予你

col2 col3                                                                        dict_col
col1                                                                                          
1       a    W  [{'col1': 1, 'col2': 'a', 'col3': 'W'}, {'col1': 1, 'col2': 'b', 'col3': 'X'}]
2       c    Y  [{'col1': 2, 'col2': 'c', 'col3': 'Y'}, {'col1': 2, 'col2': 'd', 'col3': 'Z'}]

相关问题