Skip to content

Setting empty column on empty DataFrame #5632

Closed
@FragLegs

Description

@FragLegs

This issue appears in 0.13.0-rc1 and did not appear in 0.12.0-854-gde63e00

Let us say we have an empty DataFrame. Then the following calls (which worked in pandas 0.12) no longer work:

df = pd.DataFrame()
df['foo'] = []

df = pd.DataFrame()
df['foo'] = df.index

df = pd.DataFrame()
df['foo'] = range(len(df))

They all throw an exception:

File "/usr/local/lib/python3.2/dist-packages/pandas-0.13.0rc1-py3.2-linux-x86_64.egg/pandas/core/frame.py", line 1855, in __setitem__
    self._set_item(key, value)
  File "/usr/local/lib/python3.2/dist-packages/pandas-0.13.0rc1-py3.2-linux-x86_64.egg/pandas/core/frame.py", line 1915, in _set_item
    self._ensure_valid_index(value)

File "/usr/local/lib/python3.2/dist-packages/pandas-0.13.0rc1-py3.2-linux-x86_64.egg/pandas/core/frame.py", line 1899, in _ensure_valid_index
    raise ValueError('Cannot set a frame with no defined index '
ValueError: Cannot set a frame with no defined index and a non-series

The following will work:

df = pd.DataFrame()
df['foo'] = pd.Series([])

df = pd.DataFrame()
df['foo'] = pd.Series(df.index)

df = pd.DataFrame()
df['foo'] = pd.Series(range(len(df)))

The issue appears to be on lines 1897-1899 of pandas.core.frame:

if not len(self.index):
    if not isinstance(value, Series):
        raise ValueError('Cannot set a frame with no defined index '

Perhaps it could be changed to:

if not len(self.index) and len(value) > 0:
    if not isinstance(value, Series):
        raise ValueError('Cannot set a frame with no defined index '

Metadata

Metadata

Assignees

No one assigned

    Labels

    API DesignBugIndexingRelated to indexing on series/frames, not to indexes themselves

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions