Categories
Python Answers

How to append to an empty DataFrame in Python Pandas?

Spread the love

To append data to an empty DataFrame in Python Pandas, we can use the append() method.

To do this we write:

import pandas as pd

# Create an empty DataFrame
df = pd.DataFrame(columns=['Column1', 'Column2'])

# Create a dictionary with data to append
data_to_append = {'Column1': [1, 2, 3],
                  'Column2': ['A', 'B', 'C']}

# Append the data to the empty DataFrame
df = df.append(data_to_append, ignore_index=True)

print(df)

This will output:

   Column1 Column2
0        1       A
1        2       B
2        3       C

In this example, we first create an empty DataFrame df with specified column names.

We then create a dictionary data_to_append with the data we want to append to the DataFrame.

Finally, we use the append() method to append the data to the empty DataFrame df, passing ignore_index=True to reset the index of the resulting DataFrame. This ensures that the index starts from 0.

Make sure that the columns in the dictionary match the columns in the DataFrame.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *