user7786493 user7786493 - 1 year ago 95
Python Question

When we assign a variable to a single numpy.float64 via df.iloc method, will the df be exposed?

df=pd.DataFrame([[2,4,6],[5,7,8],[2,4,6],[5,7,8],[2,4,6],[5,7,8]])


0 1 2
0 2 4 6
1 5 7 8
2 2 4 6
3 5 7 8
4 2 4 6
5 5 7 8


When we assign a variable to df.iloc, say
extract=df.iloc[2:5,0:2]
, I know that the data referenced to variable extract is exposed (mutable to df). However, if I want to just reference a variable to an exact number (say,
extract=df.iloc[3,4]
), is the original df still exposed to extract? (and what is the best way to get a copy of that single number to the variable exact?) When I do
print(type(df.iloc[3,4])
, I notice the type is
<class 'numpy.float64'>
. Is this an object reference or a primitive data ?

Answer Source

No. When you assign to extract what's returned by df.iloc[3, 2] and run type(extract), you'll get numpy.int64.

You can tell that something will operate on the source dataframe by looking at the is_copy attribute.

extract = df.iloc[2:5, 0:2]

type(extract)

pandas.core.frame.DataFrame

print(extract.is_copy)

<weakref at 0x11b27cd60; to 'DataFrame' at 0x11bd64050>

So in this circumstance, extract is pointing to the same data that df is.

We can test this with various cases

extract = df.iloc[[4], 1]

type(extract)

pandas.core.series.Series

print(extract.is_copy)

None

extract = df.iloc[[2], [1]]

type(extract)

pandas.core.frame.DataFrame

print(extract.is_copy)

<weakref at 0x11b27c100; to 'DataFrame' at 0x11bd642d0>

It seems that if you slice `df` and maintain the dataframe dimensionality by using two indexers that produce arrays like `[2]`, `[0, 1]`, or `:2` then we will get a dataframe with connected data.

What about one indexer

extract = df.iloc[:2]

print(extract.is_copy)

<weakref at 0x11b27c100; to 'DataFrame' at 0x11bd642d0>

Yes, still a reference to data in df

If you want to ensure that you aren't

extract = df.iloc[[2], [1]].copy()

print(extract.is_copy)

None

Not a reference to data in df

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download