【问题标题】:How to concatenate rows side by side in pandas如何在熊猫中并排连接行
【发布时间】:2023-01-09 06:04:49
【问题描述】:

我想将同一数据集的五行组合成一个数据集 我有 700 行,我想每五行合并一次

      A  B  C  D  E  F   G
1     10,11,12,13,14,15,16    
2     17,18,19,20,21,22,23    
3     24,25,26,27,28,29,30      
4     31,32,33,34,35,36,37    
5     38,39,40,41,42,43,44
.
.
.
.
.
700

合并前五行后..我的第一行应该是这样的:

        A  B  C  D  E  F  G  A  B  C  D  E  F  G  A  B  C  D  E  F  G  A  B  C  D  E  F  G  A  B  C  D  E  F  G
                                                                         
    1  10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44

【问题讨论】:

  • 那么对于接下来的五行,您的结果 df 中将有一个单独的行?
  • 是的,正是@SomeDude
  • 我已经更新了我的答案以匹配您的编辑 @bigci10

标签: python pandas


【解决方案1】:

如果你能保证你拥有的总行数是 5 的倍数,numpy 将是解决这个问题的最有效方法:

import numpy as np
import pandas as pd

data = np.arange(70).reshape(-1, 7)
df = pd.DataFrame(data, columns=[*'ABCDEFG'])

print(df)
    A   B   C   D   E   F   G
0   0   1   2   3   4   5   6
1   7   8   9  10  11  12  13
2  14  15  16  17  18  19  20
3  21  22  23  24  25  26  27
4  28  29  30  31  32  33  34
5  35  36  37  38  39  40  41
6  42  43  44  45  46  47  48
7  49  50  51  52  53  54  55
8  56  57  58  59  60  61  62
9  63  64  65  66  67  68  69

out = pd.DataFrame(
    df.to_numpy().reshape(-1, df.shape[1] * 5),
    columns=[*df.columns] * 5
)

print(out)
    A   B   C   D   E   F   G   A   B   C   D   E   F  ...   B   C   D   E   F   G   A   B   C   D   E   F   G
0   0   1   2   3   4   5   6   7   8   9  10  11  12  ...  22  23  24  25  26  27  28  29  30  31  32  33  34
1  35  36  37  38  39  40  41  42  43  44  45  46  47  ...  57  58  59  60  61  62  63  64  65  66  67  68  69

[2 rows x 35 columns]

【讨论】:

    【解决方案2】:

    你可以做:

    cols = [col for v in [df.columns.tolist()]*len(df) for col in v]
    dfs = [df[i:min(i+5,len(df))].reset_index(drop=True) for i in range(0,len(df),5)]
    df2 = pd.concat([pd.DataFrame(df.stack()).T for df in dfs])
    df2.columns = cols
    df2.reset_index(drop=True, inplace=True)
    

    【讨论】:

    • 我有很多行
    • @bigci10 你需要在你的描述中清楚地说明你的问题
    【解决方案3】:

    看看这是否有助于回答您的问题 unstack 将列变成行,一旦我们在列中有了数据,我们只需要将其转置即可。 reset_index 将生成的系列变成数据框。原始列名称被制成索引,因此当我们转置时,我们拥有您在列中所述的列。

    df.unstack().reset_index().set_index('level_0')[[0]].T
    
    level_0 A   A   A   A   A   B   B   B   B   B   ... F   F   F   F   F   G   G   G   G   G
    0   10  17  24  31  38  11  18  25  32  39  ... 15  22  29  36  43  16  23  30  37  44
    

    如果答案有帮助,请投票和/或接受

    【讨论】:

      【解决方案4】:

      最简单的方法是将您的数据框转换为 numpy 数组,对其进行整形,然后将其转换回新的数据框。

      编辑:

      data= # your dataframe
      new_dataframe=pd.DataFrame(data.to_numpy().reshape(len(data)//5,-1),columns=np.tile(data.columns,5))
      

      【讨论】:

      • 我需要所有行。我有 700 行,我想每五行合并一次
      • 请使用更多详细信息编辑您的问题
      【解决方案5】:

      在熊猫中堆叠和拆堆叠数据

      表格中的数据通常以多种方式呈现。长格式(“整齐的数据”)是指堆叠在几列中的数据。其中一列将包含有关值的分类指标。相比之下,宽格式(“堆叠数据”)是每个类别都有自己的列。

      在您的示例中,您展示了广泛形式的数据,并且您正试图将其变成长形式。 pandas.melt、pandas.groupby、pandas.pivot、pandas.stack、pandas.unstack 和 pandas.reset_index 是帮助在这些形式之间进行转换的函数。

      从您的原始数据框开始:

      df = pd.DataFrame({
         'A' : [10, 17, 24, 31, 38],
         'B' : [11, 18, 25, 32, 39],
         'C' : [12, 19, 26, 33, 40],
         'D' : [13, 20, 27, 34, 41],
         'E' : [14, 21, 28, 35, 42],
         'F' : [15, 22, 29, 36, 43],
         'G' : [16, 23, 30, 37, 44]})
      
          A   B   C   D   E   F   G
      0   10  11  12  13  14  15  16
      1   17  18  19  20  21  22  23
      2   24  25  26  27  28  29  30
      3   31  32  33  34  35  36  37
      4   38  39  40  41  42  43  44
      

      使用 pandas.melt 将其转换为长格式,然后排序以获取您请求数据的方式:忽略索引选项有助于我们稍后将其恢复为宽格式。

      melted_df = df.melt(ignore_index=False).sort_values(by='value')
      
      
      variable    value
      0   A   10
      0   B   11
      0   C   12
      0   D   13
      0   E   14
      0   F   15
      0   G   16
      1   A   17
      1   B   18
      ...
      

      使用 groupby、unstack 和 reset_index 将其转换回宽格式。这通常是一个更加困难的过程,它依赖于按值堆叠列、其他列、索引和堆叠变量进行分组,然后取消堆叠并重置索引。

      (melted_df
          .reset_index() # puts the index values into a column called 'index'
          .groupby(['index','variable']) #groups by the index and the variable
          .value  #selects the value column in each of the groupby objects
          .mean() #since there is only one item per group, it only aggregates one item
          .unstack() #this sets the first item of the multi-index to columns
          .reset_index() #fix the index
          .set_index('index') #set index
      )
          A   B   C   D   E   F   G                           
      0   10  11  12  13  14  15  16
      1   17  18  19  20  21  22  23
      2   24  25  26  27  28  29  30
      3   31  32  33  34  35  36  37
      4   38  39  40  41  42  43  44
      

      这些东西可能非常困难,需要反复试验。我建议制作一个较小版本的问题并解决它们。这样你就可以弄清楚函数是如何工作的。

      【讨论】:

        【解决方案6】:

        尝试使用 arange()floordiv 以每 5 个为一组进行分组,然后用这些组创建一个新的 df。即使您的df 不能被 5 整除,这也应该有效。

        l = 5
        (df.groupby(np.arange(len(df.index))//l)
         .apply(lambda x: pd.DataFrame([x.to_numpy().ravel()]))
         .set_axis(df.columns.tolist() * l,axis=1)
         .reset_index(drop=True))
        

        或者

        (df.groupby(np.arange(len(df.index))//5)
        .apply(lambda x: x.reset_index(drop=True).unstack()).droplevel(1,axis=1))
        

        输出:

           A  B  C  D  E  F  G  A  B  C  ...  E  F  G  A  B  C  D  E  F  G
        0  9  0  3  2  6  2  9  1  7  5  ...  2  5  9  5  4  9  7  3  8  9
        1  9  5  0  8  1  5  8  7  7  7  ...  6  3  5  5  2  3  9  7  5  6
        

        【讨论】:

          猜你喜欢
          • 2018-11-05
          • 2020-06-16
          • 1970-01-01
          • 2023-02-04
          • 2021-11-22
          • 2015-12-23
          • 2016-03-09
          • 1970-01-01
          • 2021-08-25
          相关资源
          最近更新 更多