简体   繁体   English

如何按列的值对pandas数据帧的行进行分组?

[英]How do I group the rows of a pandas data frame by a value of a column?

How do I group the rows of a pandas data frame by a value of a column? 如何按列的值对pandas数据帧的行进行分组?

Lets say we have a data frame called df: 假设我们有一个名为df的数据框:

A   B  C
1   1a 1b
1   1c 1d
1   1e 1f
2   2a 2b
2   2c 2d
3   3a 3b
3   3c 3d

I'd like to use groupby to create the following : 我想使用groupby创建以下内容:

1: {[1a, 1b],
    [1c, 1d],
    [1e, 1f]}

2: {[2a,2b],
    [2c, 2d]}


3: {[3a,3b],
    [3c. 3d]}

I do realize .loc is an option. 我确实意识到.loc是一个选择。 But it is super slow for the super-large dataset I'm working on. 但对于我正在研究的超大型数据集来说,这是非常缓慢的。 Which is why I thought turning it in a dictionary of lists may be better. 这就是为什么我认为把它放在列表字典中可能会更好。

Thanks. 谢谢。

It seems you need: 看来你需要:

df = df.groupby('A')['B','C'].apply(lambda x: x.values.tolist()).to_dict()
print (df)
{1: [['1a', '1b'], ['1c', '1d'], ['1e', '1f']], 
 2: [['2a', '2b'], ['2c', '2d']], 
 3: [['3a', '3b'], ['3c', '3d']]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为熊猫数据框中的一组行分配组号? - How do I assign a group # to a set of rows in a pandas data frame? 如何按Pandas数据框中的列值进行分组 - How to Group by column value in Pandas Data frame 如何在 Pandas 中获取组中最大数据的列的值? - How do I get the value of the column with the max data in a group by in Pandas? 如何计算 Pandas 数据框中一组的每对行之间的函数 - How do I calculate a function between each pair of rows of a group in a pandas data frame 如何使用 pandas 根据日期列和天数列向数据框添加行 - How do I use pandas to add rows to a data frame based on a date column and number of days column 熊猫分组数据框并按列值排序 - Pandas group data frame and sort by column value 如何根据python中的pandas数据框中的列按降序分组? (Jupyter 笔记本) - How do I group by based on a column in pandas data frame in python and in descending order? (Jupyter Notebook) 按列值复制 Pandas 数据框中的行 - Replicating rows in a pandas data frame by a column value 如果列元素是一个集合,如何从 pandas 数据框列中获取每个值的计数? - How do I get count of each value from a pandas Data Frame column if the column elements is a set? 我如何在 Pandas 数据框中有条件地 select 行 - How do I conditionally select rows in a Pandas data frame by
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM