0

The following code snippet

df = pandas.DataFrame({})
for run in range(3):
     df[str(run)] = pandas.Series([1,2])

produces an empty dataframe (instead of three columns of [1,2], indexed by 0, 1, 2). Why, and how do I fix this?

More precisely, this is what is output by pandas version 0.11 (run in ipython with Python 2.7):

In [17]: df
Out[17]:
Empty DataFrame
Columns: [0, 1, 2]


Index: []

2 Answers 2

1

Works fine in 0.13

In [1]: df = pandas.DataFrame({})

In [2]: for run in range(3):
   ...:          df[str(run)] = pandas.Series([1,2])
   ...:     

In [3]: df
Out[3]: 
   0  1  2
0  1  1  1
1  2  2  2

[2 rows x 3 columns]

Much more efficient to do this, however

In [8]: df = pd.concat([ pandas.Series([1,2]) for i in range(3) ], axis=1)

In [9]: df
Out[9]: 
   0  1  2
0  1  1  1
1  2  2  2

[2 rows x 3 columns]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. My example is a simplified version of what I need to do and the workaround won't work for that unfortunately.
ok. just add then to a list, it IS quite inefficient to add one at a time.
0

I can't reproduce. Try again.

In [8]: df = DataFrame({})

In [9]: for run in range(3):
         df[str(run)] = Series([1,2])
   ...: 

In [10]: df
Out[10]:
   0  1  2
0  1  1  1
1  2  2  2

[2 rows x 3 columns]

If it fails, what version of pandas? (Though I'm almost certain this is fine in any version.)

2 Comments

Pandas version 0.11... Thanks!
I have no idea what the problem is. Maybe try Jeff's way as a "workaround"? But this should be working fine.

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.