Creating a new data frame pandas
You can create a new DataFrame in pandas using the pd.DataFrame()
function. Here is a basic example:
import pandas as pd
# Create a dictionary
data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 24, 35, 32],
'Country': ['USA', 'UK', 'Australia', 'Germany']}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
print(df)
In this example, we first import the pandas library and then create a dictionary with three keys: 'Name', 'Age', and 'Country'. Each key has a list of values. We then convert this dictionary into a DataFrame using the pd.DataFrame()
function. The resulting DataFrame is then printed.
Here is the output:
Name Age Country
0 John 28 USA
1 Anna 24 UK
2 Peter 35 Australia
3 Linda 32 Germany
You can also create a DataFrame from a list of lists:
import pandas as pd
data = [['John', 28, 'USA'],
['Anna', 24, 'UK'],
['Peter', 35, 'Australia'],
['Linda', 32, 'Germany']]
df = pd.DataFrame(data, columns=['Name', 'Age', 'Country'])
print(df)
This will produce the same output as the previous example.
You can also create a DataFrame from a numpy array:
import pandas as pd
import numpy as np
data = np.array([['John', 28, 'USA'],
['Anna', 24, 'UK'],
['Peter', 35, 'Australia'],
['Linda', 32, 'Germany']])
df = pd.DataFrame(data, columns=['Name', 'Age', 'Country'])
print(df)
This will also produce the same output as the previous examples.