Appending to an empty DataFrame in Pandas?

PythonPandas

Python Problem Overview


Is it possible to append to an empty data frame that doesn't contain any indices or columns?

I have tried to do this, but keep getting an empty dataframe at the end.

e.g.

import pandas as pd

df = pd.DataFrame()
data = ['some kind of data here' --> I have checked the type already, and it is a dataframe]
df.append(data)

The result looks like this:

Empty DataFrame
Columns: []
Index: []

Python Solutions


Solution 1 - Python

That should work:

>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
   A
0  0
1  1
2  2

But the append doesn't happen in-place, so you'll have to store the output if you want it:

>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
   A
0  0
1  1
2  2

Solution 2 - Python

And if you want to add a row, you can use a dictionary:

df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)

which gives you:

   age  height name
0    9       2  Zed

Solution 3 - Python

You can concat the data in this way:

InfoDF = pd.DataFrame()
tempDF = pd.DataFrame(rows,columns=['id','min_date'])

InfoDF = pd.concat([InfoDF,tempDF])

Solution 4 - Python

I tried this way and it works

import pandas as pd

df = pd.DataFrame(columns =['columnA','columnB'])
data = {'columnA':'data', 'columnB':'data'}
df = df.append(data)

Solution 5 - Python

> pandas.DataFrame.append Deprecated since version 1.4.0: Use concat() instead.

Therefore:

df = pd.DataFrame() # empty dataframe
df2 = pd..DataFrame(...) # some dataframe with data

df = pd.concat([df, df2])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionericmjlView Question on Stackoverflow
Solution 1 - PythonDSMView Answer on Stackoverflow
Solution 2 - PythondvalView Answer on Stackoverflow
Solution 3 - PythonDeepishView Answer on Stackoverflow
Solution 4 - PythonW KennyView Answer on Stackoverflow
Solution 5 - PythonWtowerView Answer on Stackoverflow