Python - Transform range of rows into columns [closed]

0

I have a DataFrame with one column and 5,000 rows.

What I need to do is pick up 48-line breaks and transpose to 48 columns with the entire dataFrame

How are you?

 1. 0.35
 2. 0.21
 3. 0.45
 4. ...
 5. 0.12
 6. 0.34 

As required:

[0.35 0.21 0.45 ... 0.12 0.34]
    
asked by anonymous 18.03.2018 / 20:53

1 answer

1

I've made code that can be changed for several amounts of rows to be transposed into columns. First, I created a DataFrame with 40 elements (1, 2, ..., 40) in a column and stored its dimensions:

import pandas as pd
dados = list(range(1, 41, 1))
dados= pd.DataFrame(dados)
nlinhas,ncols=dados.shape

Result of print(dados.head()) :

ThenIsethowmanycolumnstheDataFramewiththetransposeddatashouldhave.Inmyexample,Ichose6,inyourswouldbe48.Basedonnumberofelements(numberofrows)andnumberofcolumns,IcreatealistwiththeinitialindicesofeachrowinthenewDataFrame.

#númerodecolunasnoDataFrameasercriado(transposto):ncolunas=6lista=list(range(0,nlinhas,ncolunas))

TheDataFrame.append()joinsthedatabasedonthenameofthecolumns.Therefore,forthedatatobealigned,theymustalwayshavecolumnsofthesamename.A%void%iscreatedtostorethetransposeddataandthecolumnsarenamed(C0,C1,...,C5):

colnomes=["C"+str(i) for i in range(0, ncolunas)]
dados_transpostos = pd.DataFrame(columns=colnomes)

Finally, a DataFrame iterates over the index list values, transposes the columns of interest, checks for the expected number of columns - if it does not exist, adds -, renames the columns and appends to the created% to store the transposed data.

for i in lista:
    df=dados[i:i+ncolunas].transpose()
    if df.shape[1] != len(colnomes):
        addcol = len(colnomes)-df.shape[1]
        df = pd.concat([df, pd.DataFrame(columns=['B'+str(i) for i in range(0, addcol)])])
    df.columns = dados_transpostos.columns.values
    dados_transpostos= dados_transpostos.append(df, ignore_index = True)

print(dados_transpostos)

Result:

    
19.03.2018 / 15:31