Adding elements to an empty dataframe in pandas

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!

Upvotes: 1

Views: 3726

Answers (2)

the_economist
the_economist

Reputation: 551

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.

Upvotes: 0

lstodd
lstodd

Reputation: 168

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

Upvotes: 1

Related Questions