The Python Oracle

Appending a list or series to a pandas DataFrame as a row?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Melt

--

Chapters
00:00 Question
00:25 Accepted answer (Score 173)
00:46 Answer 2 (Score 176)
00:56 Answer 3 (Score 70)
01:11 Answer 4 (Score 41)
01:31 Thank you

--

Full question
https://stackoverflow.com/questions/2630...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas #append #dataframe

#avk47



ACCEPTED ANSWER

Score 183


Sometimes it's easier to do all the appending outside of pandas, then, just create the DataFrame in one shot.

>>> import pandas as pd
>>> simple_list=[['a','b']]
>>> simple_list.append(['e','f'])
>>> df=pd.DataFrame(simple_list,columns=['col1','col2'])
   col1 col2
0    a    b
1    e    f



ANSWER 2

Score 71


Here's a simple and dumb solution:

>>> import pandas as pd
>>> df = pd.DataFrame()
>>> df = df.append({'foo':1, 'bar':2}, ignore_index=True)



ANSWER 3

Score 42


Could you do something like this?

>>> import pandas as pd
>>> df = pd.DataFrame(columns=['col1', 'col2'])
>>> df = df.append(pd.Series(['a', 'b'], index=['col1','col2']), ignore_index=True)
>>> df = df.append(pd.Series(['d', 'e'], index=['col1','col2']), ignore_index=True) 
>>> df
  col1 col2
0    a    b
1    d    e

Does anyone have a more elegant solution?




ANSWER 4

Score 33


Following onto Mike Chirico's answer... if you want to append a list after the dataframe is already populated...

>>> list = [['f','g']]
>>> df = df.append(pd.DataFrame(list, columns=['col1','col2']),ignore_index=True)
>>> df
  col1 col2
0    a    b
1    d    e
2    f    g