Python pandas df.copy () не глубоко - PullRequest
0 голосов
/ 03 мая 2020

У меня (на мой взгляд) странная проблема с python pandas. Если я сделаю:

cc1 = cc.copy(deep=True)

для кадра данных cc, а затем спросить определенную строку и столбец:

print(cc1.loc['myindex']['data'] is cc.loc['myindex']['data'])

Я получу

True

Что не так здесь

1 Ответ

0 голосов
/ 04 мая 2020

Глубокое копирование не работает в pandas, и разработчики рассматривают возможность размещения изменяемых объектов внутри DataFrame как антипаттерна

В вашем коде нет ничего плохого, на всякий случай, если вы хотите узнать разницу с некоторым примером глубокого и мелкого копирования () здесь это.

Глубокая копия

dict_1= {'Column A': ['House','Animal', 'car'],
     'Column B': ["walls,doors,rooms", "Legs,nose,eyes", "tires,engine" ]}

df1 = pd.DataFrame(dict_1, columns=['Column A', 'Column B'])

# Deep copy
df2 = df1.copy()  #  deep=True by default
df2 == df1  # it returns True because no updates has happened on either of dfs
output
#   Column A    Column B
# 0 True    True
# 1 True    True
# 2 True    True

id(df1)  # output: 2302063108040
id(df2)  # ouptut: 2302063137224

Теперь, если вы обновите столбец B со значением df1

dict_new =  {'Column A': ['House','Animal', 'car'],
     'Column B': ["walls", "Legs,nose,eyes,tail", "tires,engine,bonnet" ]}

# updating only column B values
df1.update(dict_new)

df1 == df2   # it returns false for the values which got changed

вывод:

    Column A    Column B
0   True    False
1   True    False
2   True    False

И если мы увидим глубоко скопированный df1 #, он останется неизменным

df1
# output:
# Column A  Column B
# 0 House   walls,doors,rooms
# 1 Animal  Legs,nose,eyes
# 2 car tires,engine

Мелкая копия

df2 = df1.copy(deep=False)  #  deep=True by default hence explicitly providing argument to False
df2 == df1  # it returns True because no updates has happened on either of dfs
# output
#   Column A    Column B
# 0 True    True
# 1 True    True
# 2 True    True

dict_new =  {'Column A': ['House','Animal', 'car'],
     'Column B': ["walls", "Legs,nose,eyes,tail", "tires,engine,bonnet" ]}

df1.update(dict_new)

df2 == df1  # since it has same reference of d1 you will see all true even after updating column B unlike deep copy
# output
#   Column A    Column B
# 0 True    True
# 1 True    True
# 2 True    True

df2  # now if you see df2 it has all those updated values of df1

# output:
#   Column A    Column B
# 0 House   walls
# 1 Animal  Legs,nose,eyes,tail
# 2 car tires,engine,bonnet

Источник: python Pandas Копия DataFrame (глубокая = ложная) против копии (глубокая = истинная) против '=' https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.copy.html

...