📜  如何列出每个 Pandas 组的值?

📅  最后修改于: 2022-05-13 01:54:26.350000             🧑  作者: Mango

如何列出每个 Pandas 组的值?

在本文中,我们将了解如何显示数据帧所划分的每个组的所有值。首先使用DataFrame.groupby()方法将数据帧分组。然后我们对其进行修改,使每个组都包含列表中的值。

首先,让我们创建一个数据框:

Python3
# import pandas library
import pandas as pd
  
# create a dataframe
df = pd.DataFrame({'a': ['A', 'A', 'B',
                          'B', 'B', 'C',
                          'C', 'D'], 
                    'b': [1, 2, 5,
                          3, 5, 4,
                          8, 6]})
# show the dataframe                  
df


Python3
# import pandas library
import pandas as pd
  
# create a dataframe
df = pd.DataFrame({'a': ['A', 'A', 'B',
                          'B', 'B', 'C',
                          'C', 'D'], 
                    'b': [1, 2, 5,
                          3, 5, 4,
                          8, 6]})
                   
# convert values of each group
# into a list
groups = df.groupby('a')['b'].apply(list)
  
print(groups)
  
# groups store in a new 
# column called listvalues
df1 = groups.reset_index(name 
                         = 'listvalues')
# show the dataframe
df1


Python3
# import pandas library
import pandas as pd
  
# create a dataframe
df = pd.DataFrame( {'a': ['A', 'A', 'B',
                         'B', 'B', 'C', 
                         'C', 'D'], 
                    'b': [1, 2, 5, 
                         3, 5, 4,
                         8, 6]}
                 )
# convert values of each group
# into a list
groups = df.groupby('a').agg(lambda
                             x: list(x))
  
print(groups)


输出:

数据框

方法一:使用 DataFrame.groupby()Series.apply() 一起。
示例:我们将创建每个组的所有值的列表,并将其存储在名为“listvalues”的新列中。

Python3

# import pandas library
import pandas as pd
  
# create a dataframe
df = pd.DataFrame({'a': ['A', 'A', 'B',
                          'B', 'B', 'C',
                          'C', 'D'], 
                    'b': [1, 2, 5,
                          3, 5, 4,
                          8, 6]})
                   
# convert values of each group
# into a list
groups = df.groupby('a')['b'].apply(list)
  
print(groups)
  
# groups store in a new 
# column called listvalues
df1 = groups.reset_index(name 
                         = 'listvalues')
# show the dataframe
df1

输出:

分组到列表中

方法二:使用 DataFrame.groupby()Series.agg()

示例:我们使用Series.agg()中的lambda函数将组的所有值转换为列表。

Python3

# import pandas library
import pandas as pd
  
# create a dataframe
df = pd.DataFrame( {'a': ['A', 'A', 'B',
                         'B', 'B', 'C', 
                         'C', 'D'], 
                    'b': [1, 2, 5, 
                         3, 5, 4,
                         8, 6]}
                 )
# convert values of each group
# into a list
groups = df.groupby('a').agg(lambda
                             x: list(x))
  
print(groups)

输出:

分组到列表中