Skip to content

Assignments: numerics, strings and .loc #6171

Closed
@aldanor

Description

@aldanor

Why would assigning an entire column to an array of values work differently with numbers vs strings?

Assigning numeric values:

>>> df = pd.DataFrame(columns=['x', 'y'])
>>> df['x'] = [1, 2]
>>> df
   x    y
0  1  NaN
1  2  NaN

Assigning string values:

>>> df = pd.DataFrame(columns=['x', 'y'])
>>> df['x'] = ['1', '2']
ValueError: could not broadcast input array from shape (2) into shape (0)

Btw according to latest docs .loc can append, but can it append more than one value at once?

Setting multiple via .loc:

>>> df = pd.DataFrame(columns=['x', 'y'])
>>> df.loc[:, 'x'] = [1, 2]
>>> df
Empty DataFrame
Columns: [x, y]
Index: []
>>> df.loc[[0, 1], 'x'] = [1, 2]
>>> df
Empty DataFrame
Columns: [x, y]
Index: []
>>> df.loc[0:2, 'x'] = [1, 2]
>>> df
Empty DataFrame
Columns: [x, y]
Index: []

Setting single via .loc: (this works ofc)

>>> df = pd.DataFrame(columns=['x', 'y'])
>>> df.loc[0, 'x'] = 1
>>> df
   x    y
0  1  NaN

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugDtype ConversionsUnexpected or buggy dtype conversionsIndexingRelated 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