Creating a Pandas DataFrame
×


Creating a Pandas DataFrame

895

Creating an Empty DataFrame

In data analysis, there are times when you need a blank canvas—a DataFrame without any initial data. This is where an empty DataFrame comes in handy.

import pandas as pd

# Creating an empty DataFrame
df_empty = pd.DataFrame()

print(df_empty)
Output:

Empty DataFrame
Columns: []
Index: []

Building a DataFrame from a List

You can construct a simple DataFrame using a Python list. Each element of the list will become a row in the resulting DataFrame.

import pandas as pd

data = ['Red', 'Green', 'Blue']

df = pd.DataFrame(data, columns=['Colors'])

print(df)
Output:

  Colors
0    Red
1  Green
2   Blue

Creating a DataFrame from a Dictionary

One of the most common ways to create a DataFrame is from a dictionary. Keys become column names, and values become the data.

import pandas as pd

data = {
    'Name': ['John', 'Jane', 'Jack'],
    'Score': [85, 90, 95]
}

df = pd.DataFrame(data)

print(df)
Output:

   Name  Score
0  John     85
1  Jane     90
2  Jack     95

Generating a DataFrame from NumPy Arrays

When dealing with numeric datasets, NumPy arrays integrate seamlessly with Pandas DataFrames.

import pandas as pd
import numpy as np

arr = np.array([[10, 20], [30, 40]])

df = pd.DataFrame(arr, columns=['X', 'Y'])

print(df)
Output:

    X   Y
0  10  20
1  30  40

Loading Data from Files

Real-world data often comes from files. Pandas makes it simple to load data from CSV and Excel formats.

import pandas as pd

# Reading a CSV file
df_csv = pd.read_csv('file.csv')

# Reading an Excel file
df_excel = pd.read_excel('file.xlsx')

print(df_csv.head())

Conclusion

Creating a DataFrame in Pandas is flexible and intuitive. Whether starting from scratch or importing external data, you can quickly shape your dataset into a structure ready for analysis. Mastering these creation techniques is a vital step in becoming proficient with Pandas.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat