1

I am new to Python and have a basic question. I have an empty dataframe Resulttable with columns A B and C which I want to keep filling with the answers of some calculations which I run in a loop represented by the loop index n. For ex. I want to store the value 12 in the nth row of column A, 35 in nth row of column B and so on for the whole range of n.

I have tried something like

Resulttable['A'].iloc[n] = 12
Resulttable['B'].iloc[n] = 35

I get an error single positional indexer is out-of-bounds for the first value of n, n=0. How do I resolve this? Thanks!

2 Answers2

1

You can first create an empty pandas dataframe and then append rows one by one as you calculate. In your range you need to specify one above the highest value you want i.e. range(0, 13) if you want to iterate for 0-12.

import pandas as pd

df = pd.DataFrame([], columns=["A", "B", "C"])
for i in range(0, 13):
    x = i**1
    y = i**2
    z = i**3
    df_tmp = pd.DataFrame([(x, y, z)], columns=["A", "B", "C"])
    df = df.append(df_tmp)

df = df.reset_index()

This will result in a DataFrame as follows:

df.head()
index   A   B   C
0   0   0   0   0
1   0   1   1   1
2   0   2   4   8
3   0   3   9   27
4   0   4   16  64
lstodd
  • 168
  • 2
  • 9
0

There is no way of filling an empty dataframe like that. Since there are no entries in your dataframe something like

Resulttable['A'].iloc[n]

will always result in the IndexError you described. Instead of trying to fill the dataframe like that you better store the results from your loop in a list which you could call 'result_list'. Then you can create a dataframe using your list like that:

Resulttable= pd.DataFrame({"A": result_list})

If you've got another another list of results you want to store in another column of your dataframe, let's say result_list2, then you can create your dataframe like that:

Resulttable= pd.DataFrame({"A": result_list, "B": result_list2})

If 'Resulttable' has already been created you can add column B like that

Resulttable["B"] = result_list2

I hope I could help you.

the_economist
  • 487
  • 1
  • 8
  • 20
  • Thanks! I tried your method. To store the results in a list, I again created an empty list and used 'append' to keep adding elements to it. Then that becomes just like the other answer suggested here to use 'append' with the df instead. Is this the way to fill up the lists or is there an alternative? – Chandramouli Santhanam Apr 11 '19 at 08:27
  • There are more elegant ways I think but it is fine to do it like that. – the_economist Apr 15 '19 at 20:20