Pandas version checks
-
[X] I have checked that this issue has not already been reported.
-
[X] I have confirmed this bug exists on the latest version of pandas.
-
[ ] I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import pandas as pd
# init pandas DataFrame from dictionary
d = {'Labels': {0: {'id1': {'value': True}}}}
df = pd.DataFrame(data=d) # 'data=d.copy()' holds same result
# copy dataframe
df_copy = df.copy(deep=True)
# update Labels column using loc
df_copy["Labels"].loc[0]["id1"]["value"] = False
# print to see what has changed
print(df_copy)
print(df)
print(d)
Issue Description
Dataframe copy does not work as expected when changing the new dataframe with .loc function if the records that is changed is part of a dictionary. The original dataframe and dictionary are changed as well, when changes are applied to the new dataframe. The .copy() function should prevent this kind of behaviour.
Expected Behavior
I expect that both df
and d
in the code example are unaffected by the changes made to df_copy
, since we are working with the .copy()
functionality. This is the case for other data types (as suggested here, so I do not understand why this is different for dictionaries. I find it particularly interesting that the original dictionary is update as well if we use .loc
on the pandas DataFrame.
When using the following code the dictionary is unaffected df = pd.DataFrame(data=copy.deepcopy(d))
, but the issue with the dataframes still remains.