如何聚合熊猫中的列

时间:2021-02-16 23:40:06

标签: python pandas

我有一个包含列数的数据框,我想将它们分组到两个主要组 A 和 B 下,同时将旧列名称保留为字典,如下所示

index userid  col1  col2  col3  col4  col5 col6 col7
0      1        6    3    Nora  100    11   22    44

所需的数据框如下

index userid                 A                                             B 
0      1    {"col1":6, "col2":3, "col3":"Nora","col4":100}    {"col5":11, "col6":22, "col7":44}

3 个答案:

答案 0 :(得分:1)

你可以试试这样的:

d = {'col1': 'A',
     'col2': 'A',
     'col3': 'A',
     'col4': 'A',
     'col5': 'B',
     'col6': 'B', 
     'col7': 'B'}

df.groupby(d, axis=1).apply(pd.DataFrame.to_dict, orient='series').to_frame().T

输出:

                                                   A                                           B
0  {'col1': [6], 'col2': [3], 'col3': ['Nora'], '...  {'col5': [11], 'col6': [22], 'col7': [44]}

答案 1 :(得分:1)

要精确匹配您想要的数据框:

>>> import pandas as pd

# recreating your data
>>> df = pd.DataFrame.from_dict({'index': [0], 'userid': [1], 'col1': [6], 'col2': [3], 'col3': ['Nora'], 'col4': [100], 'col5': [11], 'col6': [22], 'col7': [44]})

# copy of unchanged columns
>>> df_new = df[['index', 'userid']].copy()

# grouping columns together
>>> df_new['A'] = df[['col1', 'col2', 'col3', 'col4']].copy().to_dict(orient='records')
>>> df_new['B'] = df[['col5', 'col6', 'col7']].copy().to_dict(orient='records')

>>> df_new
   index  userid                                                    A                                     B
0      0       1  {'col1': 6, 'col2': 3, 'col3': 'Nora', 'col4': 100}  {'col5': 11, 'col6': 22, 'col7': 44}

答案 2 :(得分:0)

使用原始数据框。

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.clipsToBounds = false
    cell.layer.masksToBounds = false
    cell.contentView.layer.masksToBounds = false
}