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

为何Pandas中操作新初始化的DataFrame会修改原DataFrame?

Why Modifying tesla Changes Your Original df (And How to Fix It)

Hey there! Let me break down what's happening here—it's a super common gotcha with Pandas (and Python in general) that even seasoned users stumble on sometimes.

The Root Cause: References vs. Copies

When you run tesla = df, you aren't creating a brand new DataFrame. Instead, you're just assigning a new variable name (tesla) that points to the exact same object in memory as df. Think of it like giving a single house two different street addresses—changing anything inside the house affects both addresses.

So any data operation you perform on tesla is actually modifying that shared underlying object, which is why df also shows the changes.

The Fix: Use copy() to Create an Independent DataFrame

To make sure tesla is a separate, editable copy that doesn't affect df, you need to explicitly create a copy of the DataFrame using Pandas' built-in copy() method. There are two flavors depending on your needs:

  • Shallow Copy (Default): This creates a new DataFrame object, but shares any nested mutable objects (like lists or dictionaries) with the original. For most standard tabular data (numbers, strings, dates), this is more than enough:

    tesla = df.copy()
    
  • Deep Copy: If your DataFrame contains nested structures (e.g., a column with lists), use deep=True to fully duplicate every part of the DataFrame, ensuring zero shared references:

    tesla = df.copy(deep=True)
    

Example to Show the Difference

Problematic Code (References):

import pandas as pd

# Create original DataFrame
df = pd.DataFrame({'Model': ['S', '3', 'X'], 'Price': [79990, 38990, 99990]})
# Just a reference, not a copy
tesla = df
# Modify the "copy"
tesla['Price'] = tesla['Price'] - 5000
# Original df is also changed!
print(df)

Fixed Code (Independent Copy):

import pandas as pd

df = pd.DataFrame({'Model': ['S', '3', 'X'], 'Price': [79990, 38990, 99990]})
# Create a true copy
tesla = df.copy()
# Modify the copy safely
tesla['Price'] = tesla['Price'] - 5000
# Original df remains unchanged
print(df)
print(tesla)

Why You Might Not Have Seen This Before

It's easy to miss this behavior if you've been using operations that automatically return copies (like df.loc[:, ['col1', 'col2']] or df.query()) instead of direct variable assignment. Direct assignment is one of the clearest cases where Python's reference-based object model shows through.

内容的提问来源于stack exchange,提问作者Mohammed Yusuf Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:41:50