2

The outcome of this case:

df = _pd.DataFrame({'a':['1','2','3']})

df['b'] = _np.nan

for index in df.index:

    df.loc[index, 'b'] = [{'a':1}]

is:

    a   b
0   1   {'a': 1}
1   2   [{'a': 1}]
2   3   [{'a': 1}]

The outcome of this case:

df = _pd.DataFrame({'a':[1,2,3]})

df['b'] = _np.nan

for index in df.index:

    df.loc[index, 'b'] = [{'a':1}]

is:

    a   b
0   1   {'a': 1}
1   2   {'a': 1}
2   3   {'a': 1}

Why?

_pd.__version__
'0.23.4'

Edit: I want to add the version number, because this might be a bug. That seems reasonable to me. But, this new hold-your-hand system we have here at stackoverflow.com won't let me do it; hence I am adding this edit in order to meet the character requirement.

  • 1
    This is possibly a bug with `loc`, but in general if you are trying to assign a value to a single cell, you need to use `.at`: `df.at[index, 'b'] = [{'a':1}]` or `df.at[index, 'b'] = {'a':1}`, as appropriate. – cs95 Mar 24 '19 at 21:43
  • See [this answer](https://stackoverflow.com/a/54399996/4909087) for more info. – cs95 Mar 24 '19 at 21:44
  • 1
    @coldspeed As an aside, .at exhibits the same phenomenon. –  Mar 24 '19 at 21:59
  • `pandas` behaves really weirdly when assigning iterables to columns and to cells. I'd recommend against doing it every time. – rafaelc Mar 24 '19 at 22:01

1 Answers1

1

I think this is cause by the type transform when you assign object to a float type columns, the first item need to convert the whole columns type from float to object , then the whole column became object and the index number 1,2 will be the right type assign since the column itself already become object

df = pd.DataFrame({'a':['1','2','3']})
df['b'] = np.nan
df['b']=df['b'].astype(object)
for index in df.index:
    df.loc[index, 'b'] = [{'a':1}]
    print(df.loc[index, 'b'] ,index)

[{'a': 1}] 0
[{'a': 1}] 1
[{'a': 1}] 2
df
   a           b
0  1  [{'a': 1}]
1  2  [{'a': 1}]
2  3  [{'a': 1}]

Also , I think this may belong to the topic https://github.com/pandas-dev/pandas/issues/11617

BENY
  • 317,841
  • 20
  • 164
  • 234