You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas DataFrame赋值后操作同步问题解惑:为何修改副本会影响原DataFrame?

Why Modifying df_temp Affects df_input (And How copy() Fixes It)

Great question! This is a super common "gotcha" with mutable objects in Python—including Pandas DataFrames. Let's break down exactly what's happening here:

The Problem with df_temp = df_input

When you write df_temp = df_input, you're not creating a new DataFrame. Instead, you're just assigning a new variable name that points to the exact same object in memory as df_input. Think of it like putting a second label on the same jar of cookies—if you take a cookie out using one label, the jar under the other label will also have one less cookie.

In your code, when you run df_temp.drop(index=sample.index, inplace=True), the inplace=True flag tells Pandas to modify the DataFrame directly (instead of returning a new modified copy). Since df_temp and df_input are references to the same object, this change shows up in both variables.

How df_input.copy() Solves It

Calling df_temp = df_input.copy() creates a new, independent DataFrame with its own separate space in memory. Now df_temp is a duplicate of the original df_input, so any modifications you make to df_temp (like the in-place drop) won't touch the original df_input at all.

A Quick Side Note on Shallow vs Deep Copies

By default, copy() does a "shallow copy"—this copies the DataFrame structure and references to the data values. For most cases (like the diamonds dataset, which uses basic data types like numbers and strings), this is totally fine. If your DataFrame had nested mutable objects (like lists inside cells), you'd want to use df_input.copy(deep=True) to make sure those inner objects are also copied, but that's not necessary here.

Let's Confirm with Your Code

In your original code, after the loop runs, df_input would be empty because every drop on df_temp was modifying the same underlying object. Switching to copy() ensures df_input stays intact while you manipulate df_temp to build your sampled DataFrame.

内容的提问来源于stack exchange,提问作者Bertie Bravage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 08:42:51