Home > Blockchain >  Transform list in a dataframe (breaking elements by interval of rows)
Transform list in a dataframe (breaking elements by interval of rows)

Time:03-20

I'm trying to append a list to a dataframe in Python I want to put the first 6 numbers on the same line and then add it line by line, until complete the dataframe. I tried to generate the data to make it easier:

import pandas as pd
import random

randomlist = []
for i in range(0,30):
    n = random.randint(1,30)
    randomlist.append(n)

resultado(randomlist)
randomlist = 30, 11, 18, 11, 28, 18, 22, 18, 20, 10, 11, 6, 29, 1, 11, 15, 3, 4, 17, 11, 17, 18, 27, 25, 11, 10, 7, 4, 18, 27

lista_colunas = ['Carro', 'Moto', 'Barco', 'Patinete', 'Mobilete', 'Skate]
lista_index = ['Entre 1 a 5', 'Entre 6 a 10', 'Entre 11 a 15', 'Entre 16 a 20', 'Entre 21 a 25']

Expected outcome:

1

CodePudding user response:

I'd suggest directly using NumPy instead.

import numpy as np
import pandas as pd

# 1, 30 are the boundaries of the values;
# (5, 6) is the shape of the resulting matrix
df = pd.DataFrame(np.random.randint(1, 30, (5, 6)), index=lista_index, columns=lista_colunas)

Result:

>>> df
               Carro  Moto  Barco  Patinete  Mobilete  Skate
Entre 1 a 5       20     8     24        21        29     15
Entre 6 a 10      16     3     29        29        21     27
Entre 11 a 15     25     8     27        29        25     23
Entre 16 a 20     18    27     22         3        23      7
Entre 21 a 25     22     2      2        17         4     12

CodePudding user response:

You need to firstly reshape your list and afterwards give the arguments to the dataFrame. This should work:

import pandas as pd
import numpy as np

randomlist = [30, 11, 18, 11, 28, 18, 22, 18, 20, 10, 11, 6, 29, 1, 11, 15, 3, 4, 17, 11, 17, 18, 27, 25, 11, 10, 7, 4, 18, 27]

lista_colunas = ['Carro', 'Moto', 'Barco', 'Patinete', 'Mobilete', 'Skate']
lista_index = ['Entre 1 a 5', 'Entre 6 a 10', 'Entre 11 a 15', 'Entre 16 a 20', 'Entre 21 a 25']

randomlist = np.reshape(randomlist, (len(lista_index), len(lista_colunas)))
df = pd.DataFrame(randomlist, index = lista_index, columns=lista_colunas)

print(df.head())

Hope this could help.

  • Related