【问题标题】:How to automatically split table into subtables containing two consecutive rows?如何自动将表拆分为包含两个连续行的子表?
【发布时间】:2021-10-24 02:25:46
【问题描述】:

我有这样的表:

value1 value2
a g
b h
c i
d j
e k
f l

我想自动将表拆分为包含两个连续行的子表,如下所示:

表1:

value1 value2
a g
b h

表2:

value1 value2
b h
c i

表3:

value1 value2
c i
d j

table4:

value1 value2
d j
e k

表5:

value1 value2
e k
f l

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    一个有趣的替代方法是使用 Numpy 中的 as_strided 函数和 将结果保存为 DataFrame 列表。

    从必要的导入开始:

    from numpy.lib.stride_tricks import as_strided as stride
    

    然后定义如下函数:

    def decompose(df, rowNo):
        v = df.values
        d0, d1 = v.shape
        s0, s1 = v.strides
        a = stride(v, (d0 - (rowNo - 1), w, d1), (s0, s0, s1))
        return [ pd.DataFrame(a[i], columns=df.columns) for i in range(a.shape[0]) ]
    

    当你调用它时:

    result = decompose(df, 2)
    

    结果是包含原始特定片段的 DataFrame 列表 数据帧。

    例如result[0] 包含:

      value1 value2
    0      a      g
    1      b      h
    

    如果您想将此列表的每个元素保存在一个单独的基本变量下, 自己做吧。

    【讨论】:

    • 不确定下注,功能很好 imo。
    【解决方案2】:

    遍历数据框并使用locals动态创建变量:

    for i in range(len(df)-1):
        locals()[f"table{i+1}"] = df[i:i+2].reset_index(drop=True)
    
    >>> table1
      value1 value2
    0      a      g
    1      b      h
    
    >>> table2
      value1 value2
    0      b      h
    1      c      i
    
    ...
    
    >>> table5
      value1 value2
    0      e      k
    1      f      l
    

    如果您希望索引在 tableX 中保留,请删除 .reset_index(...)

    【讨论】:

      【解决方案3】:

      使用字典推导和 groupby,因为你想要连续的行,你可以使用 floor division 来创建你的 groupby 对象。

      tables = {f"table{x+1}" : y for x,y in df.groupby(df.index // 2) }
      
      
      print(tables['table1'])
      
        value1 value2
      0      a      g
      1      b      h
      

      tables.keys()
      dict_keys(['table1', 'table2', 'table3'])
      

      【讨论】:

        猜你喜欢
        • 2019-09-18
        • 2015-03-08
        • 1970-01-01
        • 2022-06-21
        • 1970-01-01
        • 1970-01-01
        • 2020-05-03
        • 1970-01-01
        相关资源
        最近更新 更多