Programming

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

procodes 2020. 2. 19. 22:15
반응형

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 countin 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 ()는 고유 한 groupby count를 가져오고 reset_index () 메소드는 원하는 열의 이름을 재설정합니다. 마지막으로 pandas Dataframe () 함수가 호출되어 DataFrame 객체를 만듭니다.


어쩌면 나는 질문을 오해 할 수 있지만 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()

Qty 현명한 데이터로 집계하여 데이터 프레임에 저장했습니다.

almo_grp_data = pd.DataFrame({'Qty_cnt' :
almo_slt_models_data.groupby( ['orderDate','Item','State Abv']
          )['Qty'].sum()}).reset_index()

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

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

핵심은 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에 새 데이터 프레임이 있습니다 .

결과 데이터 프레임


이 솔루션은 여러 집계를 수행했기 때문에 부분적으로 만 효과가있었습니다. 다음은 데이터 프레임으로 변환하려는 그룹화 된 샘플 출력입니다.

그룹 별 출력

reset_index ()에서 제공하는 것보다 많은 수를 원했기 때문에 위의 이미지를 데이터 프레임으로 변환하는 수동 방법을 작성했습니다. 나는 이것이 매우 장황하고 명백하기 때문에 이것을하는 가장 파이썬 / 팬더 방법은 아니라는 것을 이해하지만 그것은 내가 필요한 전부였습니다. 기본적으로 위에서 설명한 reset_index () 메소드를 사용하여 "스캐 폴딩"데이터 프레임을 시작한 다음 그룹화 된 데이터 프레임에서 그룹 쌍을 반복하고, 인덱스를 검색하고, 그룹화되지 않은 데이터 프레임에 대해 계산을 수행하고, 새로운 집계 데이터 프레임에서 값을 설정하십시오. .

df_grouped = df[['Salary Basis', 'Job Title', 'Hourly Rate', 'Male Count', 'Female Count']]
df_grouped = df_grouped.groupby(['Salary Basis', 'Job Title'], as_index=False)

# Grouped gives us the indices we want for each grouping
# We cannot convert a groupedby object back to a dataframe, so we need to do it manually
# Create a new dataframe to work against
df_aggregated = df_grouped.size().to_frame('Total Count').reset_index()
df_aggregated['Male Count'] = 0
df_aggregated['Female Count'] = 0
df_aggregated['Job Rate'] = 0

def manualAggregations(indices_array):
    temp_df = df.iloc[indices_array]
    return {
        'Male Count': temp_df['Male Count'].sum(),
        'Female Count': temp_df['Female Count'].sum(),
        'Job Rate': temp_df['Hourly Rate'].max()
    }

for name, group in df_grouped:
    ix = df_grouped.indices[name]
    calcDict = manualAggregations(ix)

    for key in calcDict:
        #Salary Basis, Job Title
        columns = list(name)
        df_aggregated.loc[(df_aggregated['Salary Basis'] == columns[0]) & 
                          (df_aggregated['Job Title'] == columns[1]), key] = calcDict[key]

사전이 아닌 경우 for 루프에서 계산을 인라인으로 적용 할 수 있습니다.

    df_aggregated['Male Count'].loc[(df_aggregated['Salary Basis'] == columns[0]) & 
                                (df_aggregated['Job Title'] == columns[1])] = df['Male Count'].iloc[ix].sum()

참고 URL : https://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-output-from-series-to-dataframe



반응형