Create a new dataframe in pandas
Here is an example of how to create a new DataFrame in pandas:
import pandas as pd
# create a dictionary to store the data
data = {'Name': ['John', 'Mary', 'David', 'Emily'],
'Age': [25, 31, 42, 28],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']}
# create a DataFrame from the dictionary
df = pd.DataFrame(data)
print(df)
This will output:
Name Age City
0 John 25 New York
1 Mary 31 Los Angeles
2 David 42 Chicago
3 Emily 28 Houston
You can also create a DataFrame from a list of dictionaries:
data = [{'Name': 'John', 'Age': 25, 'City': 'New York'},
{'Name': 'Mary', 'Age': 31, 'City': 'Los Angeles'},
{'Name': 'David', 'Age': 42, 'City': 'Chicago'},
{'Name': 'Emily', 'Age': 28, 'City': 'Houston'}]
df = pd.DataFrame(data)
print(df)
This will output the same result as above.
You can also create a DataFrame from a NumPy array:
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pd.DataFrame(data, columns=['A', 'B', 'C'])
print(df)
This will output:
A B C
0 1 2 3
1 4 5 6
2 7 8 9
You can also create a DataFrame from a CSV file:
df = pd.read_csv('data.csv')
This will read the data from the file data.csv
and create a DataFrame from it.
You can also create a DataFrame from a SQL database:
import pandas as pd
import sqlite3
conn = sqlite3.connect('database.db')
df = pd.read_sql_query('SELECT * FROM table_name', conn)
This will read the data from the table table_name
in the database database.db
and create a DataFrame from it.
These are just a few examples of how to create a new DataFrame in pandas. There are many other ways to create a DataFrame, depending on the type of data you have and the format you want to use.