Iterate a list in order to create a dataframe output Pandas

Viewed 104

Dearall, I need your help to fine tune my code in Python, Pandas.

I have a list: my_list = [405218,405211,309211,234589]

I want to iterate this list, using each element to do an elaboration that generates an output represented by a dataframe of 1 rows and 25 columns. I want then to create a dataframe where each row represents 1 output, so that I have a dataframe with all my output. In this example as my list is based on 4 item, the dataframe result will be a dataframe of 25 columns and 4 rows.

Thanks for any suggestion,

1 Answers

So I'm assuming you want to populate the row with the same number. If that's the case you can simply create a 2d list with 25 rows each row has that list. You'll get something like this:-

[[405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589],
 [405218, 405211, 309211, 234589]]

Now you just have to take the tranpose of it using numpy and make it a dataframe using pandas.

my_list = [405218,405211,309211,234589]
df = pd.DataFrame(np.array([my_list for _ in range(25)]).T)

You'll get the following dataframe as output.

DataFrame

Hope it answered your query.

Related