Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split pandas dataframe based on groupby

I want to split the following dataframe based on column ZZ

df =          N0_YLDF  ZZ        MAT     0  6.286333   2  11.669069     1  6.317000   6  11.669069     2  6.324889   6  11.516454     3  6.320667   5  11.516454     4  6.325556   5  11.516454     5  6.359000   6  11.516454     6  6.359000   6  11.516454     7  6.361111   7  11.516454     8  6.360778   7  11.516454     9  6.361111   6  11.516454 

As output, I want a new DataFrame with the N0_YLDF column split into 4, one new column for each unique value of ZZ. How do I go about this? I can do groupby, but do not know what to do with the grouped object.

like image 445
user308827 Avatar asked May 16 '14 01:05

user308827


People also ask

How do you split DataFrame by Groupby?

Step 1: split the data into groups by creating a groupby object from the original DataFrame; Step 2: apply a function, in this case, an aggregation function that computes a summary statistic (you can also transform or filter your data in this step); Step 3: combine the results into a new DataFrame.

What does Group_by do in pandas?

What is the GroupBy function? Pandas' GroupBy is a powerful and versatile function in Python. It allows you to split your data into separate groups to perform computations for better analysis.

How do I get Groupby columns in pandas?

You can also reset_index() on your groupby result to get back a dataframe with the name column now accessible. If you perform an operation on a single column the return will be a series with multiindex and you can simply apply pd. DataFrame to it and then reset_index. Show activity on this post.


2 Answers

gb = df.groupby('ZZ')     [gb.get_group(x) for x in gb.groups] 
like image 106
qwwqwwq Avatar answered Oct 04 '22 20:10

qwwqwwq


There is another alternative as the groupby returns a generator we can simply use a list-comprehension to retrieve the 2nd value (the frame).

dfs = [x for _, x in df.groupby('ZZ')] 
like image 24
Anton vBR Avatar answered Oct 04 '22 20:10

Anton vBR