Skip to content

Using assign to place values from a dict into an empty dataframe adds the column names, but no values #17847

Closed
@rs481

Description

@rs481
summary= pd.DataFrame()

myData = dict()

myData['B'] = 7
myData['C'] = -9

summary = summary.assign(**myData)

The result of

print(summary)

is

Empty DataFrame
Columns: [B, C]
Index: []

This occurs without error or warning messages.

If this had been done to a dataframe with some data already in a column called 'A' then the result would have been a data frame with:

A B C
1 7 -9

I believe that assign should work consistently whether or not there is already data in the dataframe, creating an index if necessary. The current behaviour to add columns, but not to add any data rows, and not raise an exception or warning allows problems to occur silently.

I would expect the outcome of assigning myData to an empty dataframe to be:

B C
7 -9

This problem is worse than it initially appears to be, as operations adding more data to the "empty" dataframe (with some columns) via assign will succeed.

Once written out to file the dataframe will have less data than it has columns

summary= pd.DataFrame()

myData = dict()

myData['B'] = 7
myData['C'] = -9

summary = summary.assign(**myData)

myOtherData = dict()

myOtherData['D'] = 3
myOtherData['E'] = 4

summary = summary.assign(**myData)

summary.to_csv("summary.txt", sep=" ", header=True, index_label='rep')

gives as summary.txt

B C D E
3 4

Which is clearly malformed.

Output of pd.show_versions()

[paste the output of pd.show_versions() here below this line]

pandas.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.4.3.final.0
python-bits: 64
OS: Linux
OS-release: 3.13.0-126-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_GB.UTF-8
LOCALE: en_GB.UTF-8

pandas: 0.20.3
pytest: None
pip: 1.5.4
setuptools: 3.3
Cython: 0.25.2
numpy: 1.13.1
scipy: 0.13.3
xarray: None
IPython: 1.2.1
sphinx: 1.6.3
patsy: None
dateutil: 2.6.1
pytz: 2017.2
blosc: None
bottleneck: None
tables: 3.1.1
numexpr: 2.6.2
feather: None
matplotlib: 1.3.1
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: 4.2.1
html5lib: 0.999
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.9.6
s3fs: None
pandas_gbq: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions