How to properly add a single item to a series of list data type? I tried to make a copy and add an item to the list but this method affects the original dataframe instead
This is my code:
df = pd.DataFrame({'num':[['one'],['three'],['five']]})
# make copy of original df
copy_df = df.copy()
# add 'thing' to every single list
copy_df.num.apply(lambda x: x.append('thing'))
# show results of copy_df
print(copy_df) # this will show [['one', 'thing'], ['three', 'things'], ...]
print(df) # this will also show [['one', 'thing'], ['three', 'things'], ...]
# WHY?
My question is:
Because you are copying the dataframe but not the list in dataframe so inner series still have reference of list from original dataframe.
Better way to achieve it;
copy_df.num = copy_df.num.apply(lambda x: x + ['thing'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With