中的列值分组来拆分DataFrame

中的列值分组来拆分DataFrame

本文介绍了通过将 pandas 中的列值分组来拆分DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataFrame

I have a DataFrame

S   C
3   2
3   2
3   2
3   2
3   2
3   2
1   4
1   4
1   4
1   4
1   4
1   4

如何拆分数据帧,以便一个数据帧在S和C中具有3和2,而另一个数据在S和C中具有1和4

How can i split the dataframe so that one dataframe has 3 and 2 in S and C and other has 1 and 4 in S and C

推荐答案

groupby

  1. 关键元素是 df.groupby ,它提供了您想要的分组.
  2. 但是,您需要将其简化为一个列表,以便将其拆分"为单独的数据帧.
  3. 您可以遍历groupby对象,该对象将传递一个元组,其中第一个元素是组的名称(我们用 _ 对其进行屏蔽),第二个元素是单个数据帧.
  4. li>
  5. 通过理解,我们可以遍历groupby并捕获每个元组的第二个元素...从而创建一个数据帧列表.
  1. The key element is df.groupby which provides the grouping you desire.
  2. However, you need to facilitate this into a list so that you have "split" it into separate data frames.
  3. You can iterate through the groupby object which passes a tuple where the first element is the name of the group (we mask this with _) and the second element is the individual data frame.
  4. By using a comprehension, we can iterate through the groupby and capture the second element of each tuple... thus creating a list of data frames.

请参阅:
> 列表理解
分组材料

list_of_df = [g for _, g in df.groupby(['NUMBER_OF_TRIPS', 'SERVICE_CLASS'])]

print(*list_of_df, sep='\n\n')

    NUMBER_OF_TRIPS  SERVICE_CLASS
6                 1              4
7                 1              4
8                 1              4
9                 1              4
10                1              4
11                1              4

   NUMBER_OF_TRIPS  SERVICE_CLASS
0                3              2
1                3              2
2                3              2
3                3              2
4                3              2
5                3              2

这篇关于通过将 pandas 中的列值分组来拆分DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:18