pandas - Python: Inserting a Row into a Data Frame -
is there more pythonic way insert row data frame? feel has functionality of pandas can not find it. especially, there way 'reset' indices?
thank you.
data = {'state': ['ohio', 'ohio', 'ohio', 'nevada', 'nevada'], 'year': [2000, 2001, 2002, 2001, 2002], 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]} frame = pd.dataframe(data) new = pd.dataframe(np.zeros(len(frame.columns)).reshape(1,len(frame.columns)),columns=frame.columns) row = 3 def insert_row(frame,new,row): top = frame[0:row] bottom = frame[row:] return pd.concat((top,new,bottom))
however, running above returns:
pop state year 0 1.5 ohio 2000 1 1.7 ohio 2001 2 3.6 ohio 2002 0 0.0 0 0 3 2.4 nevada 2001 4 2.9 nevada 2002
if current function works enough you, suggest adding reset_index
returned result. see below:
...: return pd.concat((top,new,bottom)).reset_index(drop=true) in [17]: new_frame = insert_row(frame, new, row) in [18]: new_frame out[18]: pop state year 0 1.5 ohio 2000 1 1.7 ohio 2001 2 3.6 ohio 2002 3 0.0 0 0 4 2.4 nevada 2001 5 2.9 nevada 2002
the parameter drop=true
forces drop old index. leaving @ false
keeps old index new first column.
Comments
Post a Comment