Letâs discuss how to create an empty DataFrame and append rows & columns to it in Pandas and Python . There are multiple ways in which we can do this task. Here we will cover the following section:
Creating an empty Dataframe in Pandas Append row to Dataframe in Pandas Append row to Dataframe in Pandas Creating empty Dataframe Creating an Empty DataFrame object.
Python3
import pandas as pd
df = pd.DataFrame()
print(df)
Output:
Empty DataFrame Columns: [] Index: [] Append Column to Dataframe to Empty DataFrame Example 1: Create a complete empty DataFrame without any column name or indices and then append columns in Pandas one by one to it.
Python3
import pandas as pd
df = pd.DataFrame()
print(df)
df['Name'] = ['Ankit', 'Ankita', 'Yashvardhan']
df['Articles'] = [97, 600, 200]
df['Improved'] = [2200, 75, 100]
df
Output:
Example 2: This method will create a new Dataframe with a new column added to the old Dataframe using assign in Pandas.
Python3
import pandas as pd
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Height': [5.1, 6.2, 5.1, 5.2],
'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
df = pd.DataFrame(data)
df2 = df.assign(address=['Delhi', 'Bangalore', 'Chennai', 'Patna'])
print(df2)
Output:
Append row to Empty DataFrame Example 1: Create an empty DataFrame with columns name only then append rows one by one to it using append() method .
Python3
import pandas as pd
df = pd.DataFrame(columns = ['Name', 'Articles', 'Improved'])
print(df)
df = df.append({'Name' : 'Ankit', 'Articles' : 97, 'Improved' : 2200},
ignore_index = True)
df = df.append({'Name' : 'Aishwary', 'Articles' : 30, 'Improved' : 50},
ignore_index = True)
df = df.append({'Name' : 'yash', 'Articles' : 17, 'Improved' : 220},
ignore_index = True)
df
Output:
Example 2: Create an empty DataFrame with a column name and indices and then append rows one by one to it using the loc[] method.
Python3
import pandas as pd
df = pd.DataFrame(columns = ['Name', 'Articles', 'Improved'],
index = ['a', 'b', 'c'])
print("Empty DataFrame With NaN values : \n\n", df)
df.loc['a'] = ['Ankita', 50, 100]
df.loc['b'] = ['Ankit', 60, 120]
df.loc['c'] = ['Harsh', 30, 60]
df
Output:
Last Updated :
29 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...