Skip to content

Instantly share code, notes, and snippets.

@tugloo1
Last active February 2, 2018 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tugloo1/9ee85c856ce058f10bd256683fbaf12f to your computer and use it in GitHub Desktop.
Save tugloo1/9ee85c856ce058f10bd256683fbaf12f to your computer and use it in GitHub Desktop.
from pandas import DataFrame, Series
a = [1, 2, 3, 4]
b = a.append(5)
print(a)
# [1, 2, 3, 4, 5]
print(b)
# None
# This makes sense as append modifies the original list but does NOT create a new list, so b is set to None. Pandas however..is the opposite
data = [['Roger Federer', 20], ['Rafael Nadal', 16]]
column_titles = ['Tennis Player', 'Number of Grand Slams']
data_frame = DataFrame(data=data, columns=column_titles)
print(data_frame)
'''
Tennis Player Number of Grand Slams
0 Roger Federer 20
1 Rafael Nadal 16
'''
# So far so good
new_row = Series(['Novak Djokovic', 12], index=column_titles)
data_frame.append(new_row, ignore_index=True)
print(data_frame)
'''
Tennis Player Number of Grand Slams
0 Roger Federer 20
1 Rafael Nadal 16
'''
# WAIT WHAT THE HELL IS THIS? Turns out, append returns a new data frame that you have to reassign
data_frame = data_frame.append(new_row, ignore_index=True)
print(data_frame)
'''
Tennis Player Number of Grand Slams
0 Roger Federer 20
1 Rafael Nadal 16
2 Novak Djokovic 12
'''
# It works but god damn it, why does pandas go against the "edit object in place" paradigm that every other programming language uses
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment