Anne
Anne

Reputation: 7022

Python: Pandas Dataframe is empty after adding columns

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: []

Upvotes: 0

Views: 126

Answers (2)

Jeff
Jeff

Reputation: 128948

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]

Upvotes: 1

Dan Allan
Dan Allan

Reputation: 35235

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.)

Upvotes: 0

Related Questions