簡體   English   中英

Python/Pandas 新手:重新分配給新變量時,對 dataframe 進行了不必要的更改

[英]Python/Pandas Novice: unwanted changes to dataframe are carrying through when reassigning to a new variable

我有一個名為 df 的數據框,我在其中應用了一些簡單的轉換(刪除列、替換值等)。 我正在執行的工作需要我擁有 2 個數據框副本; 一個有變化,一個在原來的 state 中。 這是我正在經歷的一個例子:

import pandas as pd

df=pd.read_csv(x)
df=df2
#created a data frame called df2 that should reflect all changes in df at this point (i.e. I want the file to remain in its original state)

#changes are then made to df

print(df)
#some output

print(df2)
#all changes made to df are now showing in df2, which is what I don't want

很明顯,我不完全了解數據幀在 Python 中的運行方式,我來自 R 背景。 這是正常的行為,還是不應該發生的事情? 我怎么能 go 關於在其轉換的早期階段復制 dataframe 而沒有將這些更改傳遞到另一個包含 df 內容的變量? 當我鍵入此內容時,我意識到我可能只需要使用不同的名稱再次導入文件。 我希望這很清楚,希望了解這里發生的事情。 謝謝大家的幫助。

您應該嘗試使用副本function。 當您將df分配給df2時,如果不使用副本 function ,則dfdf2都將指向同一個 object。

import pandas as pd

df=pd.read_csv(x)
df2=df.copy()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM