How to create a new dataframe in python
There are several ways to create a new DataFrame in Python using the Pandas library. Here are a few examples:
Method 1: From a dictionary
You can create a DataFrame from a dictionary where the keys are column names and the values are lists or NumPy arrays.
import pandas as pd
data = {'Name': ['John', 'Mary', 'David'],
'Age': [25, 31, 42],
'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)
print(df)
Output:
Name Age City
0 John 25 New York
1 Mary 31 Los Angeles
2 David 42 Chicago
Method 2: From a list of dictionaries
You can create a DataFrame from a list of dictionaries, where each dictionary represents a row in the DataFrame.
import pandas as pd
data = [{'Name': 'John', 'Age': 25, 'City': 'New York'},
{'Name': 'Mary', 'Age': 31, 'City': 'Los Angeles'},
{'Name': 'David', 'Age': 42, 'City': 'Chicago'}]
df = pd.DataFrame(data)
print(df)
Output:
Name Age City
0 John 25 New York
1 Mary 31 Los Angeles
2 David 42 Chicago
Method 3: From a NumPy array
You can create a DataFrame from a NumPy array, where each row in the array corresponds to a row in the DataFrame.
import pandas as pd
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)
Output:
A B C
0 1 2 3
1 4 5 6
2 7 8 9
Method 4: From a CSV file
You can create a DataFrame from a CSV file using the read_csv
function.
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
Make sure to replace 'data.csv'
with the path to your CSV file.
These are just a few examples of how to create a new DataFrame in Python using Pandas. There are many other ways to create a DataFrame, depending on your specific use case.