如何使用 groupby 与 Pandas 进行拆分、转置和合并?

问题描述 投票:0回答:2

有一个数据框,其中行上每个月和年(列名称“月和年”)有一些参数:2024 年 1 月、2023 年 12 月等;以及列上的天数 (1-31) 。

 #mydataframe

in: 
    dataframe.head()

out: 

    Month&Year  parameter   1   2   3   ..  31
    Jan 2024    rate    22  1   7       6
    Jan 2024    pressure    67  8   8       8
    Jan 2024    cut 2   67  7       2
    Dec 2023    rate    8   9   1       0
    Dec 2023    pressure    6   8   11      3
    Dec 2023    cut 7   8   77      8

我想我需要使用 groupby 来将此数据帧拆分为多个数据帧,转置每个新数据集,然后再次合并它们,因为目标是以这种方式呈现数据:

    Month&Year  parameter   rate    pressure    cut
    Jan 2024    1   22  67  2
    Jan 2024    2   1   8   67
    Jan 2024    3   7   8   7
    ..          
    Jan 2024    31  6   8   2
                
    Dec 2023    1   8   6   7
    Dec 2023    2   9   8   8
    Dec 2023    3   1   11  77
    ..          
    Dec 2023    31  0   3   8

我使用 groupby 并将此数据帧拆分为单独的数据帧

in:
    mo=dataframe.groupby('Month&year')
    dataframe_months=[mo.get_group(x) for x in mo.groups]
    print ("result: \"n", dataframe_months)


out:

    Month&Year  parameter   1   2   3   ..  31
    Jan 2024    rate    22  1   7       6
    Jan 2024    pressure    67  8   8       8
    Jan 2024    cut 2   67  7       2
                                                
                        
    Month&Year  parameter   1   2   3   ..  31
    Dec 2023    rate    8   9   1       0
    Dec 2023    pressure    6   8   11      3
    Dec 2023    cut 7   8   77      8

您能否建议我如何引用分割的数据帧,而无需手动编写它们的名称(有很多年)来按与以前相同的顺序转置它们和 megre。谢谢你

group-by merge split transpose
2个回答
0
投票

我正在尝试解决完全相同的问题。

我的数据如下:

在应用我的 groupby 内容后,我不知道如何将其放回到一个数据帧中:

def add_fifteen_minute_interval_to_beginning_of_ts(df_15_or_45):
    #print(df_15_or_45)
    new_row = pd.Series({'ts': df_15_or_45[timestamp_column_name].iloc[0],
                      'ts_future': df_15_or_45[timestamp_column_name].iloc[0] + pd.Timedelta("00:15:00"),
                      'forecast': np.nan}).to_frame().T
    df_15_or_45 = pd.concat([new_row,df_15_or_45])
    return df_15_or_45

df_2 = df.groupby('ts',as_index=False).apply(lambda x: add_fifteen_minute_interval_to_beginning_of_ts(x) if x.iloc[0]['ts'].minute in (0, 30) else x)

给我这个输出:

问题是我只想将函数应用于原始数据框中的某些组,然后使数据框除了更改的组之外仍然完好无损。

我现在最好的猜测是:

  1. 手动覆盖旧行并连接新行
  2. 或者只是从 group by 中获取索引,然后在那里应用我的解决方案
  3. 以某种方式使用转换函数https://pandas.pydata.org/docs/user_guide/groupby.html

我会在弄清楚并更多地了解您的问题后更新我的答案😄

这最终成为我的解决方案——使用 groupby.apply() 和一个简单的函数。

就像我在评论中所说 - 如果您需要将它们堆叠起来,请先尝试 pd.concat,但这个答案可能就是您正在寻找的:迭代后合并组


0
投票

是什么让您相信必须使用 groupby 将数据框转变为所需的方式?

为了清晰起见,重复输入数据

df = pd.DataFrame({'Month&Year': ['Jan 2024','Jan 2024','Jan 2024','Dec 2023','Dec 2023','Dec 2023'],
                   'parameter': ['rate', 'pressure', 'cut', 'rate', 'pressure', 'cut'],
                   1: [22, 67, 2, 8, 6, 7],
                   2: [1, 8, 67, 9, 8, 8],
                   3: [7, 8, 7, 1, 11, 77],
                   31: [6, 8, 2, 0, 3, 8]})
df

  Month&Year parameter   1   2   3  31
0   Jan 2024      rate  22   1   7   6
1   Jan 2024  pressure  67   8   8   8
2   Jan 2024       cut   2  67   7   2
3   Dec 2023      rate   8   9   1   0
4   Dec 2023  pressure   6   8  11   3
5   Dec 2023       cut   7   8  77   8

旋转“月和年”并将日期放在同一侧

dfp = pd.pivot_table(data    = df,
                     values  = [1,2,3,31],
                     columns = 'Month&Year',
                     index   = 'parameter'
                    ).T.reset_index(    
                    ).rename(columns = {'level_0' : 'Day'})

parameter  Day Month&Year  cut  pressure  rate
0            1   Dec 2023    7         6     8
1            1   Jan 2024    2        67    22
2            2   Dec 2023    8         8     9
3            2   Jan 2024   67         8     1
4            3   Dec 2023   77        11     1
5            3   Jan 2024    7         8     7
6           31   Dec 2023    8         3     0
7           31   Jan 2024    2         8     6

您所需的输出数据框显示“参数”作为保存天数的列的名称。这感觉很混乱,所以我将其命名为“Day”。

按日期排序 这是另一个涉及 pandas.datetime 的问题。

© www.soinside.com 2019 - 2024. All rights reserved.