2

I'm confused why the following pandas does not successfully assign the last two values of column A to the first two entries of column B:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7], 'B': [10, 20, 30, 40, 50, 60, 70]})
df = df.join(pd.DataFrame({'C': ['a', 'b', 'c', 'd', 'e', 'f', 'g']}))
df['B2'] = df.B.shift(2)
df[:2].B2 = list(df[-2:].A)

What's perplexing to me is that in an (apparently) equivalent "real" application, it does appear to work (and to generate some strange behavior).

Why does the final assignment fail to change the values of the two entries in the dataframe?

1 Answer 1

5

It can work and that's why its insidious, see here: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

Generally with multi-dtyped frames it depends on the construction of when it would work (e.g. if you create it all at once, I think it will always work). Since you are creating it after (via join) it is dependent on the underlying numpy view creation mechanisms.

don't ever ever ever assign like that, use loc

df.loc[:2,'B2'] = ....
2
  • It seemed a bit too "clever" to be wise! Could the fact that it did work in the linked question account for the (to me) odd alignment behavior there?
    – orome
    Mar 17, 2014 at 15:24
  • seems likely; the data may or may not be correctly assigned.
    – Jeff
    Mar 17, 2014 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.