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())
:
ThenIsethowmanycolumnstheDataFrame
withthetransposeddatashouldhave.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: