如何制作包含数据帧的数据帧的深度副本?(Python)

2024-05-20 14:17:58 发布

您现在位置: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

这个问题的解决方法是什么?


Tags: 数据importselfdfas副本pdprint
1条回答
网友
1楼 · 发布于 2024-05-20 14:17:58

这是解决方法:

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

这就解决了问题!你知道吗

相关问题 更多 >