Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

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

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?

For example,

letters = pd.DataFrame({'Letters' : ['A', 'B', 'C','D', 'E', 'F', 'G', 'H', 
'I','J']})

Letters
0   A
1   B
2   C
3   D
4   E
5   F
6   G
7   H
8   I
9   J

and I want to reshape it like this with filling zeroes, where there is no value.

first   second  third
A       B       C
D       E       F
G       H       I
J       0       0

In numpy reshape method as far as I know you need to explicitly identify, how much columns and rows you want..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...