我的目標是使用 my_function 更改資料幀 df,然后將結果分配給資料幀 df。但是當我使用函式時,函式外部的資料幀 df 發生了變化。我怎樣才能修改函式而不影響函式之外的 df 變數?
import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30]}, index=['2021-11-24', '2021-11-25', '2021-11-26'])
def my_function(df_temp):
df_temp['A'][0] = 100 # How could I modify not to affect df varable which is outside of funtion
return df_temp
something = my_function(df)
print(df) # df is already altered although I didn't assign
# df = my_function(df)
# print(df)
uj5u.com熱心網友回復:
試試這些解決方案
- 使用 pandas.apply 函式
import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30]}, index=['2021-11-24', '2021-11-25', '2021-11-26'])
def my_function(row):
row[0] = 100
return row
something = df.apply(my_function)
print(something)
A
2021-11-24 100
2021-11-25 20
2021-11-26 30
print(df)
A
2021-11-24 10
2021-11-25 20
2021-11-26 30
2.使用pandas.copy函式
import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30]}, index=['2021-11-24', '2021-11-25', '2021-11-26'])
def my_function(df):
temp_df = df.copy()
temp_df['A'][0] = 100
return temp_df
something = my_function(df)
print(something)
A
2021-11-24 100
2021-11-25 20
2021-11-26 30
print(df)
A
2021-11-24 10
2021-11-25 20
2021-11-26 30
uj5u.com熱心網友回復:
在 Python 中,引數總是通過賦值傳遞,因此 DataFrame 在函式內部發生變異。首選處理參考,因為它不會影響性能。
如果您被迫保留原始物件,則可以通過手動創建副本來執行操作。
import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30]}, index=['2021-11-24', '2021-11-25', '2021-11-26'])
def my_function(df_temp):
df_temp['A'][0] = 99
dfc = df.copy()
my_function(dfc) # alter the copy
print(df) # unchanged
print(dfc) # altered
您可以在檔案中閱讀有關傳遞變數的更多資訊:https : //docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by -參考
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/368965.html
