it-source

Panda GroupBy 출력을 Series에서 DataFrame으로 변환

criticalcode 2022. 10. 31. 23:59
반응형

Panda GroupBy 출력을 Series에서 DataFrame으로 변환

이렇게 입력 데이터부터 시작합니다.

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여기 Data Frame이 있습니다.단, 다음과 같은 계층형 인덱스가 있습니다.

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

Wes의 답변을 약간 변경하고 싶습니다.버전 0.16.2는as_index=False설정하지 않으면 빈 데이터 프레임이 생성됩니다.

출처:

집계 함수는 집계 중인 그룹이 이름이 지정된 열일 경우 다음과 같은 경우 해당 그룹이 반환되지 않습니다.as_index=True(디폴트).그룹화된 열은 반환된 개체의 인덱스가 됩니다.

패스as_index=False는 집계하는 그룹이 이름 있는 열일 경우 해당 그룹을 반환합니다.

집계 함수는 반환되는 객체의 치수를 줄이는 함수입니다.다음은 예를 제시하겠습니다.mean,sum,size,count,std,var,sem,describe,first,last,nth,min,max예를 들어, 다음과 같은 일이 발생합니다.DataFrame.sum()그리고 a를 돌려받습니다.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나중에 사용할 수 있습니다.subset매개 변수 포함 및 포함name에서는, 다음과 같습니다.

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그리고.size그것이다sizeNaN 값을 카운트하는 동안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에 새로운 데이터 프레임이 추가되었습니다.

결과 데이터 프레임

간단히 말하면 다음과 같은 작업을 수행할 수 있습니다.

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()method는 원하는 열의 이름을 리셋합니다.마지막으로 판다들은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()

이하의 솔루션은, 보다 심플하게 할 수 있습니다.

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

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

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

이 솔루션들은 제가 여러 번 집약을 했기 때문에 부분적으로만 효과가 있었습니다.다음으로 데이터 프레임으로 변환하는 경우의 출력 예를 나타냅니다.

그룹별 출력

reset_index()에서 제공하는 개수 이상을 원했기 때문에 위의 이미지를 데이터 프레임으로 변환하는 수동 방식을 작성했습니다.나는 이것이 매우 장황하고 명료하기 때문에 이것을 하는 가장 버마적인/판다적인 방법이 아니라는 것을 이해하지만, 내가 필요로 하는 것은 그것뿐이었다.기본적으로 위의 reset_index() 메서드를 사용하여 "scaffolding" 데이터프레임을 시작하고 그룹화된 데이터프레임 내의 그룹 페어링을 루프하여 인덱스를 취득하고 그룹화되지 않은 데이터프레임에 대한 계산을 수행하여 새로운 집약 데이터프레임으로 값을 설정합니다.

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()

바닐라 "/"와 같은 됩니다.groupby()@Nehal은 기본적으로 @Nehal은 @Nehal은 @Nehal은 @Nehal과 같은 대답입니다. JWani와 함께 변수에 되었습니다.reset_index()이치노

fare_class = df.groupby(['Satisfaction Rating','Fare Class']).size().to_frame(name = 'Count')
fare_class.reset_index()

이 버전은 통계량에 유용한 백분율로 동일한 데이터를 반환할 뿐만 아니라 람다 함수를 포함합니다.

fare_class_percent = df.groupby(['Satisfaction Rating', 'Fare Class']).size().to_frame(name = 'Percentage')
fare_class_percent.transform(lambda x: 100 * x/x.sum()).reset_index()

      Satisfaction Rating      Fare Class  Percentage
0            Dissatisfied        Business   14.624269
1            Dissatisfied         Economy   36.469048
2               Satisfied        Business    5.460425
3               Satisfied         Economy   33.235294

예:

 grouped=df.groupby(['Team','Year'])['W'].count().reset_index()

 team_wins_df=pd.DataFrame(grouped)
 team_wins_df=team_wins_df.rename({'W':'Wins'},axis=1)
 team_wins_df['Wins']=team_wins_df['Wins'].astype(np.int32)
 team_wins_df.reset_index()
 print(team_wins_df)

group_keys=Falsegroup_by 메서드로 설정하여 그룹 키를 인덱스에 추가하지 않도록 합니다.

예:

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.groupby(["Name"], group_keys=False)

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

반응형