Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas panel: Copy versus view

Tags:

python

pandas

So basically, if I want to change data in the original df, I always have to use .loc[]. But consider the following

>>> import pandas as pd
>>> from scipy import random
>>> from numpy import arange

>>> T, N = 4, 5
>>> TIndex = arange(0, T)
>>> FIndex = arange(0, N)

>>> wp = pd.Panel(items=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'],
...               major_axis=TIndex, minor_axis=FIndex)
>>> wp.loc['a', 0, 0] = 0 
>>> df = wp.loc[0, 'a']
>>> df.loc[0, 'a'] = 'test'
>>> df.loc[0, 'a']
Out[379]: 'test'
>>> wp.loc['a', 0, 0]
Out[380]: 0

What am I doing wrong?

Also, no SettingWithCopyWarning has been thrown. I typically get these when I do these mistakes on dataframe level. This is highly irritating.

like image 613
FooBar Avatar asked Apr 29 '26 08:04

FooBar


1 Answers

I could modify both the DataFrame and the original Panel by selecting by label in the call to loc. The documentation says that loc is strictly limited to labels, so I am not sure the code you have posted can work at all: I got a KeyError: 'the label [0] is not in the [items]' when pasting the example into an IPython console (?).

Instead of

df = wp.loc[0, 'a']

do

df = wp.loc['a']

Then modify with iloc and integer indexes:

In [3]: df
Out[3]:
    0   1   2   3   4
0   0 NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN

[4 rows x 5 columns]

In [4]: df.iloc[0, 0] = 'test'

In [5]: df
Out[5]:
      0    1    2    3    4
0  test  NaN  NaN  NaN  NaN
1   NaN  NaN  NaN  NaN  NaN
2   NaN  NaN  NaN  NaN  NaN
3   NaN  NaN  NaN  NaN  NaN

[4 rows x 5 columns]

In [6]: wp.loc['a']
Out[6]:
      0    1    2    3    4
0  test  NaN  NaN  NaN  NaN
1   NaN  NaN  NaN  NaN  NaN
2   NaN  NaN  NaN  NaN  NaN
3   NaN  NaN  NaN  NaN  NaN

[4 rows x 5 columns]
like image 98
logc Avatar answered May 01 '26 23:05

logc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!