Programmer
Programmer

Reputation: 1294

Create dataframe from loop

I have a loop which runs 3 times, and each time produces 4 values, e.g. below.

for i in range(0, 3):
    val1 = something
    val2 = something
    val3 = something
    val4 = something

From this loop, how can I create a dataframe of size (3x4) as follows?

val1  val2  val3  val4
2     4     5     42
12    23    54    65 
4     12    2     89

Upvotes: 2

Views: 55

Answers (2)

Alexander
Alexander

Reputation: 109726

data = []
for i in range(0, 3):
    val1 = something
    val2 = something
    val3 = something
    val4 = something
    data.append([val1, val2, val3, val4])
df = pd.DataFrame(data, columns=['val1', 'val2', 'val3', 'val4'])

Upvotes: 2

Celius Stingher
Celius Stingher

Reputation: 18377

You can make a dictionary from those lists, and then turn them into a Dataframe. The following is an example:

import pandas as pd
example_dict = {'val1':val1,'val2':val2,'val3':val3,'val4':val4}
df = pd.DataFrame(example_dict)

And now you df is as you requested.

If you wish to do all this in a go, I would do something a bit different:

import pandas as pd
example_dict = {'val1':[],'val2':[],'val3':[],'val4':[]}
for i in range(0,3):
    example_dict['val1'].append(something)
    example_dict['val2'].append(something)
    example_dict['val3'].append(something)
    example_dict['val4'].append(something)
df = pd.DataFrame(example_dict)

Upvotes: 1

Related Questions