Tutorial: How to Create and Use a Pandas DataFrame
In this tutorial, you will learn how to create and use a Pandas DataFrame. A DataFrame is a 2-dimensional labeled data structure in Python that is similar to a table. You can use DataFrames to store and manipulate data from a variety of sources, such as CSV files, Excel spreadsheets, and databases.
To create a DataFrame, you can use the pandas.DataFrame()
function. The function takes two arguments: a list of data values, and a list of column names. For example, the following code creates a DataFrame with two columns, named "Name" and "Age":
```python import pandas as pd data = [['John', 25], ['Mary', 30], ['Peter', 22]] df = pd.DataFrame(data, columns=['Name', 'Age']) print(df) ``` ``` Name Age 0 John 25 1 Mary 30 2 Peter 22 ```
Once you have created a DataFrame, you can access its data using the .loc[]
and .iloc[]
accessors. The .loc[]
accessor takes a label as its argument, and the .iloc[]
accessor takes an integer index as its argument. For example, the following code prints the name of the first person in the DataFrame:
```python print(df.loc[0, 'Name']) ``` ``` John ```
You can also use the .head()
and .tail()
methods to view the first few rows or columns of a DataFrame. The .head()
method takes an integer argument that specifies the number of rows to display, and the .tail()
method takes an integer argument that specifies the number of rows to display. For example, the following code prints the first two rows of the DataFrame:
```python print(df.head(2)) ``` ``` Name Age 0 John 25 1 Mary 30 ```
Finally, you can use the .to_csv()
method to save a DataFrame to a CSV file. The method takes a filename as its argument. For example, the following code saves the DataFrame to a file named "dataframe.csv":
```python df.to_csv('dataframe.csv') ```
I hope this tutorial has helped you learn how to create and use a Pandas DataFrame. For more information, please refer to the Pandas documentation: <https://pandas.pydata.org/pandas-docs/stable/index.html>