0

The following commands show how to attribute to a slice:

In [81]: a=pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])

In [82]: a
Out[82]: 
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

In [83]: a.loc[1] = [10,11,12]

In [84]: a
Out[84]: 
    0   1   2
0   1   2   3
1  10  11  12
2   7   8   9

However, what I need to attribute to a sliced which is pointed by a variable. I tried

In [91]: row2 = a.loc[2]

In [92]: row2 = [13,14,15]

In [93]: a
Out[93]: 
    0   1   2
0   1   2   3
1  10  11  12
2   7   8   9

In [94]: row2
Out[94]: [13, 14, 15]

At this point, I wanted the value of "a" to be

In [96]: a
Out[96]:
    0   1   2
0   1   2   3
1  10  11  12
2  13  14  15

It's obvious that row2 is being treated as a copy of the slice, not the slice itself.

So, my question is: how do I create variable the points to the slice, and that can be use to attribute values to the elements of the original matrix?

bmello
  • 1,864
  • 3
  • 18
  • 23
  • I suggest you can't (AFAIK) this is the reason that the indexing methods were introduced in the first place to make it explicit that you want to modify the original df. You'd be better off using `row2` store the label/index value and then call `a.loc[row2]= [13,14,15]` as this would be readable and correct – EdChum May 19 '15 at 19:59
  • This `row2 = [13,14,15]` creates a totally new object. You can check with `obj1 is obj2` if both names, `obj1` and `obj2` point to the same object. You can also use `id(obj)` to find out the object ID. – Mike Müller May 19 '15 at 21:07

1 Answers1

1

Use slice to assign values:

row2[:] = [13,14,15]

This will update the content of row2 instead of the object it references to.

See How assignment works with python list slice for more details.

Community
  • 1
  • 1
zw324
  • 26,764
  • 16
  • 85
  • 118