3
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)

print(randn(5, 4))
df = pd.DataFrame( randn(5, 4), ['A', 'B', 'C', 'D', 'F'], ['W', 'X', 'Y', 'Z'] )

tmp_df = df['X'] 
print(type(tmp_df)) # Here type is Series (as expected)

tmp_df.loc[:] = 12.3
print(tmp_df)

print(df)

This code changes the content of (original) DataFrame df.

np.random.seed(101)
print(randn(5, 4))
df = pd.DataFrame( randn(5, 4), ['A', 'B', 'C', 'D', 'F'], ['W', 'X', 'Y', 'Z'] )

tmp_df = df.loc[['A', 'B'], ['W', 'X']] 
print(type(tmp_df)) # Type is DataFrame

tmp_df.loc[:] = 12.3 # whereas, here when I change the content of the tmp_df it doesn't reflect on original array.
print(tmp_df)

print(df)

So, does that mean if we slice the Series out of DataFrame, reference is passed to sliced object. Whereas, if it's DataFrame that has been sliced then it doesn't point to original DataFrame.

Please confirm whether my conclusion above is correct or not? Help would be appreciated.

1 Answers1

0

To put it in a simple manner: Indexing with lists in loc always returns a copy.

Let's work with a DataFrame df:

df=pd.DataFrame({'A':[i for i in range(100)]})
df.head(3)
Output:
0   0
1   1
2   2

When we try to do an operation on the sliced data.

h=df.loc[[0,1,2],['A']]
h.loc[:] = 12.3
h
Output of h:
0   12.3
1   12.3
2   22.3

The results don't reflect like how it happened in your case:

df.head(3)
Output:
0   0
1   1
2   2

But when you're doing this tmp_df = df['X'], the series tmp_df is referring to contents of "X" in column df. Which is meant to change when you modify tmp_df.

Raghul Raj
  • 1,428
  • 9
  • 24
  • here you've confirmed my second conclusion that it doesn't effect the DataFrame df. Whereas if you have taken the series out of the DataFrame then it would've changed the output in original DataFrame,(which happens to my first query) – abhishek jaiswal Jun 17 '20 at 13:19
  • Yeah that's correct, when you take a column value as series and make some changes to it, should affect the original dataframe as well. – Raghul Raj Jun 17 '20 at 18:32