简体   繁体   中英

How to divide first 4 list value into column in dataframe pandas

I have a Pandas DataFrame of empty values in column Something like this:

df = pd.DataFrame(columns=['A','B','C','D'])

i have a list Something like this:

list_imp  =  [1,5,7,5,2,7,4,7,2,8,8,3,0,9,6,9]

what i want is the first four values should be inserted inside column A next four values inside column B next four values inside column C and next 4 values inside column D. Is it possible to do so?

       A  B  C  D
       1  2  2  0
       5  7  8  9
       7  4  3  6
       5  7  8  9

Use np.array with np.T , to first create a matrix and then transform it to correct shape:

list_imp  =  [1,5,7,5,2,7,4,7,2,8,8,3,0,9,6,9]
df = pd.DataFrame(np.array(list_imp).reshape(-1,4).T, columns=['A', 'B', 'C', 'D'])

   A  B  C  D
0  1  2  2  0
1  5  7  8  9
2  7  4  8  6
3  5  7  3  9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM