Despite of the numerous stack overflow questions on appending data to a dataframe I could not really find an answer to the following. I am looking for a straight forward solution to append a list as last row of a dataframe. Imagine I have a simple dataframe:
indexlist=['one']
columnList=list('ABC')
values=np.array([1,2,3])
# take care, the values array is a 3x1 size array.
# row has to be 1x3 so we have to reshape it
values=values.reshape(1,3)
df3=pd.DataFrame(values,index=indexlist,columns=columnList)
print(df3)
A B C
one 1 2 3
After some operations I get the following list:
listtwo=[4,5,6]
I want to append it at the end of the dataframe. I change that list into a series:
oseries=pd.Series(listtwo)
print(type(oseries))
oseries.name="two"
now, this does not work:
df3.append(oseries)
since it gives:
A B C 0 1 2
one 1.0 2.0 3.0 NaN NaN NaN
two NaN NaN NaN 5.0 6.0 7.0
I would like to have the values under A B and C.
I also tried:
df3.append(oseries, columns=list('ABC')) *** not working ***
df3.append(oseries, ignore_index=True) *** working but wrong result
df3.append(oseries, ignore_index=False) *** working but wrong result
df3.loc[oseries.name]=oseries adds a row with NaN values
what I am looking for is a) how can I add a list to a particular index name b) how can I simple add a row of values out of a list even if I don't have a name for index (leave it empty)
Either assign in-place with
loc
:Or, use
df.append
with the second argument being aSeries
object having appropriate index and name:If you are appending to a DataFrame without an index (i.e., having a numeric index), you can use
loc
after finding the max of the index and incrementing by 1:Or, using
append
withignore_index=True
: