Home > Back-end >  how work with groups of a data set with respect of a column?
how work with groups of a data set with respect of a column?

Time:12-10

how I can fin the first and last elements of a dataframe based on a group of rows with respect of a column?

df1:=
g    col1       col2
h     1         2
h     0         1
h     7         8
h     5         2
h     0         1
k     7         3
k     2         1
k     9         1

if I wanna group the column with respect of g, and for each group and column I need the following information: first element, last element, size of the group

CodePudding user response:

IIUC, try:

df_g = df.groupby('dates1').agg(['first','last','size']).T.unstack()
df_g.columns = [f'{i}/{j}' for i, j in df_g.columns]
print(df_g)

Output:

      2020-01/first  2020-01/last  2020-01/size  2020-02/first  2020-02/last  2020-02/size
col1              7             9             3              1             0             5
col2              3             1             3              2             1             5
  • Related