0

I need to declare empty dataframe in python in order to append it later in a loop. Below the line of the declaration:

 result_table = pd.DataFrame([[], [], [], [], []], columns = ["A", "B", "C", "D", "E"])

It throws an error:

AssertionError: 5 columns passed, passed data had 0 columns

Why is it so? I tried to find out the solution, but I failed.

4
  • It seems you need result_table = pd.DataFrame(columns = ["A", "B", "C", "D", "E"] ) Commented Jan 29, 2018 at 12:48
  • 2
    The direct question has been answered... but the main question is "why do you want to append to it later"? Commented Jan 29, 2018 at 12:49
  • Can you explain how do you want in loop create rows? I think it is not good idea, the best is fill lists and then once call DataFrame constructor. Commented Jan 29, 2018 at 12:50
  • Possible duplicate of Pandas create empty DataFrame with only column names Commented Jan 29, 2018 at 13:02

3 Answers 3

0
import pandas as pd
df = pd.DataFrame(columns=['A','B','C','D','E'])

That's it!

Sign up to request clarification or add additional context in comments.

Comments

0

Because you actually pass no data. Try this

result_frame = pd.DataFrame(columns=['a', 'b', 'c', 'd', 'e'])

if you then want to add data, use

result_frame.loc[len(result_frame)] = [1, 2, 3, 4, 5]

Comments

0

I think it is better to create a list or tuples or lists and then call DataFrame only once:

L = []
for i in range(3):
    #some random data  
    a = 1
    b = i + 2
    c = i - b
    d = i
    e = 10
    L.append((a, b, c, d, e))

print (L)
[(1, 2, -2, 0, 10), (1, 3, -2, 1, 10), (1, 4, -2, 2, 10)]

result_table = pd.DataFrame(L, columns = ["A", "B", "C", "D", "E"])
print (result_table) 
   A  B  C  D   E
0  1  2 -2  0  10
1  1  3 -2  1  10
2  1  4 -2  2  10

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.