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
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
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