Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas add item to a series of list data type

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:

  1. why the method above adds element to original copy too?
  2. Is there any better way to add element to a Series of list?
like image 930
addicted Avatar asked Mar 04 '23 18:03

addicted


1 Answers

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'])
like image 197
Sunil Goyal Avatar answered Mar 16 '23 16:03

Sunil Goyal