简体   繁体   中英

Reshaping .csv data by stacking to another columns

I have the original data that looks like this

cp
-0.094391
-0.26169
-0.33073
-0.22134
-0.086641
-0.022418
0.026102
0.15488
0.31659
0.47564
0.62409
0.69289
0.66066
0.39925
-0.098799
-0.26515
-0.33076
-0.22232
-0.086641
-0.021011
0.02751
0.16129
0.31832
0.47096
0.61332
   .
   .
   .

and I want to stack all of the values by taking four values into the next column like this below. (And I want to delete 'cp' letter as well. )

-0.094391   -0.086641   0.31659    ....
-0.26169    -0.022418   0.47564    ....
-0.33073    0.026102    0.62409    ....
-0.22134    0.15488         0.69289    ....

How can I reshape this data using import csv python module?

This should do the trick. Replace the file paths with yours to make it work.

import csv

final_csv = [[] for i in range(4)]

with open("./test.csv") as myfile:
    rd = csv.reader(myfile)
    no_header_rd = list(rd)[1:]
    i = 0
    for row in no_header_rd:
        final_csv[i % 4].append(row[0])
        i += 1

with open("./output.csv", 'w') as myoutputfile:
    wr = csv.writer(myoutputfile)
    wr.writerows(final_csv)

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