About Lesson
There are several ways to create a DataFrame, ranging from manually inputting data to loading data from external files.
1. Creating DataFrame from a Dictionary
A common way to create a DataFrame is by using a dictionary, where the keys represent the column names and the values are lists (or arrays) that represent the 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)
Output:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
2. Creating DataFrame from a List of Lists
You can also create a DataFrame from a list of lists, where each inner list represents a row 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)
Output:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3. Creating DataFrame from CSV
You can read data directly from CSV files into a DataFrame using read_csv.
df = pd.read_csv('data.csv') # Assuming 'data.csv' is a valid CSV file
print(df.head())