Pandas: Append data to an empty DataFrame

Pandas: DataFrame Exercise-49 with Solution

Write a Pandas program to append data to an empty DataFrame.

Sample data:
Original DataFrame:
After appending some data:
col1 col2
0 0 0
1 1 1
2 2 2

Sample Solution :-

Python Code :

import pandas as pd
import numpy as np
df = pd.DataFrame()
data = pd.DataFrame({"col1": range(3),"col2": range(3)})
print("After appending some data:")
df = df.append(data)

Sample Output:

After appending some data:
   col1  col2
0     0     0
1     1     1
2     2     2         


The above code creates an empty Pandas DataFrame ‘df’, then creates another DataFrame called ‘data’ with two columns, ‘col1’ and ‘col2’, containing values from 0 to 2.

df = df.append(data): Here the DataFrame ‘data’ is appended to the ‘df’ DataFrame using the append() method. The resulting DataFrame, ‘df’, has the same columns as data and contains the values from data.

Finally print(df) statement outputs the contents of the df DataFrame.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to get the datatypes of columns of a DataFrame.
Next: Write a Pandas program to sort a given DataFrame by two or more columns.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value:


def tips_map_dictionary(itr, fn):
  ret = {}
  for a in itr:
    ret[a] = fn(a)
  return ret
print(tips_map_dictionary([2,4,6], lambda a: a * a))


{2: 4, 4: 16, 6: 36}


We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook