如何对其中包含数据框的数据框进行深层复制? (python)
How to make a deepcopy of a dataframe with dataframes within it? (python)
我想要一个包含数据框的数据框副本。当我在嵌套数据框中更改某些内容时,它不应在原始数据框中更改。
我有这样一个数据框:
0 1 2
0 1 2 <__main__.PossibleCombinations object at 0x000...
1 4 5 6
使用下一个代码生成:
import copy
import numpy as np
import pandas as pd
df = pd.DataFrame(data= [[1,2,3],[4,5,6]])
class PossibleCombinations:
def __init__(self, dfCombinations, numberCombinations):
self.dfCombinations = dfCombinations
self.numberCombinations = numberCombinations
df.iloc[0,2] = PossibleCombinations(pd.DataFrame(data= [[1,2,3],[4,5,6]]),6)
print(df)
当我对孔数据框和嵌套数据框进行深层复制并更改
副本中的嵌套数据框,原始值也会发生变化。
deepCopy = copy.deepcopy(df)
deepCopy.iloc[0,2].dfCombinations = copy.deepcopy(df.iloc[0,2].dfCombinations)
deepCopy.iloc[0,2].dfCombinations.iloc[0,2] = "doei"
print(deepCopy.iloc[0,2].dfCombinations)
print(" ")
print(df.iloc[0,2].dfCombinations)
输出:
0 1 2
0 1 2 doei
1 4 5 6
0 1 2
0 1 2 doei
1 4 5 6
但我想要:
0 1 2
0 1 2 doei
1 4 5 6
0 1 2
0 1 2 3
1 4 5 6
这个问题的解决方法是什么?
这是修复:
import pickle
deepCopy = pickle.loads(pickle.dumps(df))
deepCopy.iloc[0,2].dfCombinations.iloc[0,2] = "doei"
print(deepCopy.iloc[0,2].dfCombinations)
print(" ")
print(df.iloc[0,2].dfCombinations)
输出:
3
0 1 2
0 1 2 doei
1 4 5 6
0 1 2
0 1 2 3
1 4 5 6
这解决了问题!
我想要一个包含数据框的数据框副本。当我在嵌套数据框中更改某些内容时,它不应在原始数据框中更改。
我有这样一个数据框:
0 1 2
0 1 2 <__main__.PossibleCombinations object at 0x000...
1 4 5 6
使用下一个代码生成:
import copy
import numpy as np
import pandas as pd
df = pd.DataFrame(data= [[1,2,3],[4,5,6]])
class PossibleCombinations:
def __init__(self, dfCombinations, numberCombinations):
self.dfCombinations = dfCombinations
self.numberCombinations = numberCombinations
df.iloc[0,2] = PossibleCombinations(pd.DataFrame(data= [[1,2,3],[4,5,6]]),6)
print(df)
当我对孔数据框和嵌套数据框进行深层复制并更改 副本中的嵌套数据框,原始值也会发生变化。
deepCopy = copy.deepcopy(df)
deepCopy.iloc[0,2].dfCombinations = copy.deepcopy(df.iloc[0,2].dfCombinations)
deepCopy.iloc[0,2].dfCombinations.iloc[0,2] = "doei"
print(deepCopy.iloc[0,2].dfCombinations)
print(" ")
print(df.iloc[0,2].dfCombinations)
输出:
0 1 2
0 1 2 doei
1 4 5 6
0 1 2
0 1 2 doei
1 4 5 6
但我想要:
0 1 2
0 1 2 doei
1 4 5 6
0 1 2
0 1 2 3
1 4 5 6
这个问题的解决方法是什么?
这是修复:
import pickle
deepCopy = pickle.loads(pickle.dumps(df))
deepCopy.iloc[0,2].dfCombinations.iloc[0,2] = "doei"
print(deepCopy.iloc[0,2].dfCombinations)
print(" ")
print(df.iloc[0,2].dfCombinations)
输出:
3
0 1 2
0 1 2 doei
1 4 5 6
0 1 2
0 1 2 3
1 4 5 6
这解决了问题!