问题
y = pd.Series(x, copy=True,dtype=float)
z = pd.Series(x, copy=True)
a = pd.Series(x)
f = pd.Series.copy(x)
All the above expressions give the same output of x value and even after updating the x value the change is not reflecting. So I need to know what is the use of copy as argument and the series.copy() and also how to copy x series to some other series such that any changes made in x is reflected back in the new series also.
If any thing is wrong or not possible please forgive me... I'm a newbie to Python and I'm asking these questions out of my curiosity...
Thanks a lot in advance for the help!
回答1:
If we look at the source code of pandas Series
we can see the following,
def __init__(self, data=None, index=None, dtype=None, name=None,
copy=False, fastpath=False):
if not isinstance(data, SingleBlockManager):
data = SingleBlockManager(data, index, fastpath=True)
if copy:
data = data.copy()
So you have passed x
for the data
argument, therefore, the line data = data.copy()
makes a copy of x
. This should be equivalent to doing,
g = pd.Series(x.copy())
This is subtly different to pd.Series.copy(x)
which now makes a copy of the Series object itself, not the underlying x
. Therefore, the underlying x
might still be referenced by the new Series.
The idea of making a copy is that you be confident that any operations you perform on the Series
do not change the original object x
.
来源:https://stackoverflow.com/questions/48185809/copy-argument-vs-series-copy