0

I'm not sure how to explain the question so just look at the simple code.

import numpy as np
import pandas as pd

x = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
y = x
del y ["A"]
print(x)
print(y)

Output

   B
0  3
1  4
   B
0  3
1  4

As you can see, deleting a column from y deletes it from x too, is there any way to delete the column from y without deleting it on x too?

1 Answer 1

3

In your example, x and y both reference the same underlying object. If you want to make a copy of x, you can use:

y = x.copy()

Example:

x = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
y = x.copy()
del y["A"]
print(x)
print('-'*6)
print(y)

# returns:
   A  B
0  1  3
1  2  4
------
   B
0  3
1  4
Sign up to request clarification or add additional context in comments.

3 Comments

Sadly, it doesn't work, it returns: Traceback (most recent call last): File "***", line 7, in <module> del b ["A"] TypeError: 'method' object does not support item deletion
in your example, @Ryunaq it works. maybe you should update your example.
Yep it worked, I forgot to add the parenthesis to .copy, my bad, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.