Reshape dataframe to dataframe with unlimited rows and filling zeroes where no values

前端 未结 2 1103
耶瑟儿~
耶瑟儿~ 2020-12-20 02:02

Is there a way to reshape DataFrame to another with unrestricted rows. I just want a DataFrame with 3 columns, no matter how many rows is going to be in DataFrame?

F

相关标签:
2条回答
  • 2020-12-20 02:14

    Use:

    df = (pd.DataFrame(letters.groupby(letters.index // 3)['Letters']
                              .apply(list)
                              .values
                              .tolist(), columns=['first','second','third']).fillna(0))
    
    print (df)
      first second third
    0     A      B     C
    1     D      E     F
    2     G      H     I
    3     J      0     0
    
    0 讨论(0)
  • 2020-12-20 02:29

    You could use NumPy reshape. arr.reshape((-1, 3)) tells NumPy to reshape arr to shape (n, 3) where n is computed for you based on the size of arr and the size of the other given dimension(s) (e.g. in this example, the value 3).

    import numpy as np
    import pandas as pd
    
    letters = pd.DataFrame({'Letters' : ['A', 'B', 'C','D', 'E', 'F', 'G', 'H', 'I','J']})
    arr = np.empty(((len(letters) - 1)//3 + 1)*3, dtype='O')
    arr[:len(letters)] = letters['Letters']
    result = pd.DataFrame(arr.reshape((-1, 3)), columns='first second third'.split())
    result = result.fillna(0)
    print(result)
    

    prints

      first second third
    0     A      B     C
    1     D      E     F
    2     G      H     I
    3     J      0     0
    
    0 讨论(0)
提交回复
热议问题