[python] Series에서 DataFrame으로 Pandas GroupBy 출력 변환

이 같은 입력 데이터로 시작합니다

df1 = pandas.DataFrame( { 
    "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , 
    "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } )

인쇄시 다음과 같이 나타납니다.

   City     Name
0   Seattle    Alice
1   Seattle      Bob
2  Portland  Mallory
3   Seattle  Mallory
4   Seattle      Bob
5  Portland  Mallory

그룹화는 충분히 간단합니다.

g1 = df1.groupby( [ "Name", "City"] ).count()

인쇄하면 GroupBy개체가 생성됩니다 .

                  City  Name
Name    City
Alice   Seattle      1     1
Bob     Seattle      2     2
Mallory Portland     2     2
        Seattle      1     1

그러나 결국 원하는 것은 GroupBy 객체의 모든 행을 포함하는 또 다른 DataFrame 객체입니다. 다른 말로하면 다음과 같은 결과를 얻고 싶습니다.

                  City  Name
Name    City
Alice   Seattle      1     1
Bob     Seattle      2     2
Mallory Portland     2     2
Mallory Seattle      1     1

팬더 문서 에서이 작업을 수행하는 방법을 알 수 없습니다. 어떤 힌트라도 환영합니다.



답변

g1여기 입니다 DataFrame은. 그러나 계층 인덱스는 다음과 같습니다.

In [19]: type(g1)
Out[19]: pandas.core.frame.DataFrame

In [20]: g1.index
Out[20]:
MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'),
       ('Mallory', 'Seattle')], dtype=object)

아마도 당신은 이런 것을 원하십니까?

In [21]: g1.add_suffix('_Count').reset_index()
Out[21]:
      Name      City  City_Count  Name_Count
0    Alice   Seattle           1           1
1      Bob   Seattle           2           2
2  Mallory  Portland           2           2
3  Mallory   Seattle           1           1

또는 다음과 같은 것 :

In [36]: DataFrame({'count' : df1.groupby( [ "Name", "City"] ).size()}).reset_index()
Out[36]:
      Name      City  count
0    Alice   Seattle      1
1      Bob   Seattle      2
2  Mallory  Portland      2
3  Mallory   Seattle      1


답변

0.16.2 버전이 필요하기 때문에 Wes가 제공 한 답변을 약간 변경하고 싶습니다 as_index=False. 설정하지 않으면 빈 데이터 프레임이 나타납니다.

출처 :

집계 함수는 이름이 열인 경우 집계 될 그룹을 반환하지 않습니다 ( as_index=True기본값). 그룹화 된 열은 반환 된 개체의 인덱스입니다.

전달 as_index=False은 이름이 지정된 열인 경우 집계중인 그룹을 반환합니다.

기능은 예를 들어, 반환 된 객체의 크기를 줄일 사람이있다 집계 : mean, sum, size, count, std, var, sem, describe, first, last, nth, min, max. 이것은 당신이 예를 들어 DataFrame.sum()다시 얻을 때 일어나는 일 Series입니다.

nth는 감속기 또는 필터 역할을 할 수 있습니다 ( 여기 참조) .

import pandas as pd

df1 = pd.DataFrame({"Name":["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"],
                    "City":["Seattle","Seattle","Portland","Seattle","Seattle","Portland"]})
print df1
#
#       City     Name
#0   Seattle    Alice
#1   Seattle      Bob
#2  Portland  Mallory
#3   Seattle  Mallory
#4   Seattle      Bob
#5  Portland  Mallory
#
g1 = df1.groupby(["Name", "City"], as_index=False).count()
print g1
#
#                  City  Name
#Name    City
#Alice   Seattle      1     1
#Bob     Seattle      2     2
#Mallory Portland     2     2
#        Seattle      1     1
#

편집하다:

버전 0.17.1이상 에서는 subsetin count및 in reset_index매개 변수 name를 사용할 수 있습니다 size.

print df1.groupby(["Name", "City"], as_index=False ).count()
#IndexError: list index out of range

print df1.groupby(["Name", "City"]).count()
#Empty DataFrame
#Columns: []
#Index: [(Alice, Seattle), (Bob, Seattle), (Mallory, Portland), (Mallory, Seattle)]

print df1.groupby(["Name", "City"])[['Name','City']].count()
#                  Name  City
#Name    City                
#Alice   Seattle      1     1
#Bob     Seattle      2     2
#Mallory Portland     2     2
#        Seattle      1     1

print df1.groupby(["Name", "City"]).size().reset_index(name='count')
#      Name      City  count
#0    Alice   Seattle      1
#1      Bob   Seattle      2
#2  Mallory  Portland      2
#3  Mallory   Seattle      1

의 차이 count와는 sizesize동안 NaN의 값 계산 count하지 않습니다.


답변

간단히 말해서이 작업을 수행해야합니다.

import pandas as pd

grouped_df = df1.groupby( [ "Name", "City"] )

pd.DataFrame(grouped_df.size().reset_index(name = "Group_Count"))

여기 grouped_df.size()에서 고유 한 그룹 별 수를 가져 와서 reset_index()원하는 열 이름을 재설정합니다. 마지막으로 팬더 Dataframe()함수는 DataFrame 객체를 생성하기 위해 호출됩니다.


답변

핵심은 reset_index () 메소드 를 사용하는 입니다.

사용하다:

import pandas

df1 = pandas.DataFrame( {
    "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] ,
    "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } )

g1 = df1.groupby( [ "Name", "City"] ).count().reset_index()

이제 g1에 새 데이터 프레임이 있습니다 .

결과 데이터 프레임


답변

어쩌면 나는 질문을 오해 할 수 있지만 groupby를 데이터 프레임으로 다시 변환하려면 .to_frame ()을 사용할 수 있습니다. 이 작업을 할 때 색인을 재설정하고 싶었으므로 해당 부분도 포함 시켰습니다.

질문과 관련이없는 예제 코드

df = df['TIME'].groupby(df['Name']).min()
df = df.to_frame()
df = df.reset_index(level=['Name',"TIME"])


답변

나는 이것이 나를 위해 일한다는 것을 알았다.

import numpy as np
import pandas as pd

df1 = pd.DataFrame({
    "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] ,
    "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"]})

df1['City_count'] = 1
df1['Name_count'] = 1

df1.groupby(['Name', 'City'], as_index=False).count()


답변

아래 솔루션이 더 간단 할 수 있습니다.

df1.reset_index().groupby( [ "Name", "City"],as_index=False ).count()