Pandas: Append data to an empty DataFrame
49. Append Data to Empty DataFrame
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)
print(df)
Sample Output:
After appending some data: col1 col2 0 0 0 1 1 1 2 2 2
Explanation:
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.
For more Practice: Solve these Related Problems:
- Write a Pandas program to create an empty DataFrame with specified columns and then append multiple rows sequentially.
- Write a Pandas program to initialize an empty DataFrame and then add data from a dictionary row by row.
- Write a Pandas program to append data to an empty DataFrame and then convert the resulting DataFrame to a NumPy array.
- Write a Pandas program to create an empty DataFrame, append rows using a loop, and then verify the final DataFrame’s shape.
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.