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)
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.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/pandas/python-pandas-data-frame-exercise-49.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics