简体   繁体   中英

Reshaping data from 2 column using pandas

I need some help regarding on reshaping data from 2 column using pandas.

I have this csv file (test.csv)

Axe Break   Chaplin
1   52.1    ty
2   32.2    ty
3   44.6    ty
3   99.1    ty
5   122.3   ty
3   43.2    ty
7   79.4    ty
8   45.5    ty
9   56.3    ty
0   15.4    ty
1   35.7    ty
2   23.7    ty
3   66.7    ty
4   33.8    ty
1   12.9    ty
7   34.8    ty
1   21.6    ty
3   43.7    ty
6   44.2    ty
9   55.8    ty
4   22.4    ty
3   55.6    ty
2   11.4    ty
5   54.6    ty
6   19.7    ty
7   23.5    ty
1   12.8    ty
6   34.6    ty
8   69.6    ty
9   55.8    ty

Desired result is like this

[[  52.1   32.2   44.6   99.1  122.3]
 [  43.2   79.4   45.5   56.3   15.4]]
[[ 35.7  23.7  66.7  33.8  12.9]
 [ 34.8  21.6  43.7  44.2  55.8]]
[[ 22.4  55.6  11.4  54.6  19.7]
 [ 23.5  12.8  34.6  69.6  55.8]]
ty

I already tried and below is the sample script

import pandas as pd
import numpy as np

df = pd.read_csv("test2.csv")

def arrange1():
    start = 0
    for i in range(0, len(df.index)):
        if (i + 1)%10 == 0:
            result = df['Break'].iloc[start:i+1].reshape(2,5)
            start = i + 1
            print result
    print "ty"

arrange1()

Although this script does provide the result that I wanted, I feel like there is another way to do it using Pandas.

I was hoping that I did not have to do the

print "ty"

Thank you for your help.

[UPDATE]

I am sorry for not clarifying what I wanted. I want to get the result like I showed with "ty" printed at the end but I do not want to write

print "ty"

in the script. In other words,

print result

will print this output

[[  52.1   32.2   44.6   99.1  122.3]
 [  43.2   79.4   45.5   56.3   15.4]]
[[ 35.7  23.7  66.7  33.8  12.9]
 [ 34.8  21.6  43.7  44.2  55.8]]
[[ 22.4  55.6  11.4  54.6  19.7]
 [ 23.5  12.8  34.6  69.6  55.8]]
ty

Use this:

df.Break.values.reshape(3, 2, -1)

array([[[  52.1,   32.2,   44.6,   99.1,  122.3],
        [  43.2,   79.4,   45.5,   56.3,   15.4]],

       [[  35.7,   23.7,   66.7,   33.8,   12.9],
        [  34.8,   21.6,   43.7,   44.2,   55.8]],

       [[  22.4,   55.6,   11.4,   54.6,   19.7],
        [  23.5,   12.8,   34.6,   69.6,   55.8]]])

Or if you need lists

df.Break.values.reshape(3, 2, -1).tolist()

[[[52.1, 32.2, 44.6, 99.1, 122.3], [43.2, 79.4, 45.5, 56.3, 15.4]],
 [[35.7, 23.7, 66.7, 33.8, 12.9], [34.8, 21.6, 43.7, 44.2, 55.8]],
 [[22.4, 55.6, 11.4, 54.6, 19.7], [23.5, 12.8, 34.6, 69.6, 55.8]]]

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