Create a new dataframe pandas
Here is an example of how to create a new Pandas DataFrame:
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 Pandas 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')
print(df)
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)
print(df)
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 Pandas DataFrame. There are many other ways to create a DataFrame, depending on the type of data you have and the format you want to use.