为何Pandas中操作新初始化的DataFrame会修改原DataFrame?
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=Trueto 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

