How do I create a DataFrame?

094

To create a DataFrame in Python using the pandas library, you can use the pd.DataFrame() function. Here are a few common methods to create a DataFrame:

1. From a Dictionary:

You can create a DataFrame from a dictionary where keys are column names and values are lists of data.

import pandas as pd

data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
}

df = pd.DataFrame(data)
print(df)

2. From Lists:

You can also create a DataFrame from lists by specifying the column names.

import pandas as pd

data = [
    ['Alice', 25, 'New York'],
    ['Bob', 30, 'Los Angeles'],
    ['Charlie', 35, 'Chicago']
]

df = pd.DataFrame(data, columns=['Name', 'Age', 'City'])
print(df)

3. From a CSV File:

If you have data in a CSV file, you can create a DataFrame by reading the file.

import pandas as pd

df = pd.read_csv('filename.csv')
print(df)

Summary:

Choose the method that best fits your data source. If you have any specific requirements or need further examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!