1

I'm using Numpy to calculate somme formulas. I need a datafrale results with more details.

I tried something like df_append.append to load data in dataframe.

df_cars = pd.DataFrame(data= None,['CarName', "ModelName",'Month', 'values'])

for(carname in cars):
    modelsnames = getModels(car)
    for(modelname in Models):
        values=np.array(get_values(car,model))
        #values = [1,5,6,9,10,2,10,7,23,90,102,14]
        new_row={'CarName' :carname ,"ModelName": modelname, 'Month':np.arange(1,len(index)+1), 'value':index}
        df_cars = df_cars.append(new_row, ignore_index=True)

But numpy values save it in one cell(results of Numpy formula)

Example:

numpy values_BMW_Serie1 : [45000,44000,41000,45000,42000]

   Car   Model    Month  value
1  BMW   Serie1   1       [45000,44000,41000,45000,42000]

I need to save each numpy value in one cell

   Car   Model    Month  value
1  BMW   Serie1   1       45000
2  BMW   Serie1   2       44000
3  BMW   Serie1   3       41000
4  BMW   Serie1   4       45000
5  BMW   Serie1   5       42000

2
  • cars is a list of cars names like cars['BMW', 'Mercedes', 'Kia'....] ; the subjet it how to append many rows to dataframe from numpy array Commented Aug 14, 2020 at 13:42
  • You can use df_cars = df_cars.explode('value'). However, why are you looping to populate your dataframe instead of dumping all the data and filtering once it is part of the df? this way you bypass the loops and the many calls to getModels and get_values Commented Aug 14, 2020 at 13:43

1 Answer 1

3

To fixe your problem, use the explode() function:

import numpy as np

df_cars=df_cars.explode('value')

df_cars.index = np.arange(1, len(df_cars) + 1)

df_cars['Month']=df_cars.index

OUTPUT:

   Car   Model  Month  value
1  BMW  Serie1      1  45000
2  BMW  Serie1      2  44000
3  BMW  Serie1      3  41000
4  BMW  Serie1      4  45000
5  BMW  Serie1      5  42000

You can read more about explode() function on pandas.DataFrame.explode

Sign up to request clarification or add additional context in comments.

2 Comments

Does it answer you? If it is, accept it to close the question.
but i have the same value in the "Month" column?i can't explode many columns. i 'am looking for fix it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.