Ron
Ron

Reputation: 167

Why does this leave me with 2 identical DF?

I have a DF as such. I want to merge the columns:

DF=
ID    token
0     here
1     I
2     am

DF2 = DF
DF2["token"] = DF["token"] + "-" + DF["ID"].str.split(' ').str[-1]


DF2=
ID    token
0     here-0
1     I-1
2     am-2

However when I look at both DF, they look the same:

DF.to_csv("DF.csv")
DF2.to_csv("DF2.csv")

DF=
ID    token
0     here-0
1     I-1
2     am-2

DF2=
ID    token
0     here-0
1     I-1
2     am-2

Why is that? Shouldn't only DF2 have the new format??!

Upvotes: 2

Views: 52

Answers (1)

piRSquared
piRSquared

Reputation: 294488

You assigned DF2 = DF which just points the name DF2 at the same object as the name DF. That means that what ever you do to change that object is reflected when you access that object by either name.

Instead use

DF2 = DF.copy()

This will create a new object that is a copy of the object that DF points to and will be independent.

Upvotes: 2

Related Questions