简体   繁体   中英

Reshaping CSV data by stacking columns

My dataset looks like this - from a csv file

0   100   1   100   2   100  3   100  4   100  5   100     
6   200   7   200   8   200  9   200  0   200  1   200  
.....    

I want to reshape my dataset in the following format using python -

0 100
1 100
2 100
3 100
4 100
5 100
..
6 200
7 200
8 200
9 200
0 200
1 200
...

Load your data using pd.read_csv -

df = pd.read_csv('file.csv', sep='\s+', header=None)
arr = df.values

Or, using np.loadtxt -

arr = np.loadtxt('file.csv')

Now, reshape and save -

np.savetxt('file.csv', arr.reshape(-1, 2), delimiter=',')

Or, if you want the result as a dataframe -

pd.DataFrame(arr.reshape(-1, 2)).set_index(0)

     1
0     
0  100
1  100
2  100
3  100
4  100
5  100
6  200
7  200
8  200
9  200
0  200
1  200

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