2

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

2 Answers 2

2
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'])
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

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.