Jun-11-2022, 10:07 PM
(This post was last modified: Jun-11-2022, 10:07 PM by deanhystad.)
import pandas as pd rg = pd.DataFrame([['red', 0], ['green', 1]]) rgb = rg.append([['blue', 2]]) print(rg, "\n") print(rgb)
Output: 0 1
0 red 0
1 green 1
0 1
0 red 0
1 green 1
0 blue 2
Notice that the dataframe referenced by "rg" is unchanged. It only contains "red" and "green". "rgb" references a new dataframe object that was created by the append() function. This new dataframe contains the original and the new row "blue".Python lists are different. When you append to a list, the original list is modified to hold the new values.
rg = ["red", "green"] rgb = rg.append("blue") print(rg) print(rgb)
Output:['red', 'green', 'blue']
None
Notice that the list object referenced by "rg" contains the color "blue". The original list object was modified to contain the appended value. Also notice that "rgb" refrences None. It is common for Python functions to return None when they don't create any objects.Python objects live only as long as they are referenced. Unreferenced objects get garbage collected and their memory is reused to make new objects. color = "blue" assigns a str object to a variable named "color". Right now there is only one reference to the str object "blue". If I do this, color = 1, the variable color now references an int object. Now the str object "blue" is not referenced by any variables. It's reference count is zero. There is no way for me to use the str object "blue" anymore because I don't have any variables that reference it. In many languages "blue" would continue to exist in limbo, taking up space until the program ends. In Python, assigning color = 1 not only assigns color to reference an int object, it unassigns color to stop referencing the "blue" object. The "blue" object reference count drops to zero, and Python puts it in the garbage collector.
In your example where you do this: df = df.append([['grey',12]]), the variable "df" is reassigned to reference the new dataframe object created by the append() function. The original dataframe object is no longer referenced by any variables, so it gets garbage collected.
Is that clear?