Reading and Writing Data in Pandas:
Reading and Writing Data in Pandas:
Pandas provides several functions to read and write data in different formats. Here are some commonly used functions:
- Reading CSV files:
CSV (Comma Separated Values) is a file format used to store tabular data, such as spreadsheets. The read_csv()
function in Pandas is used to read data from a CSV file.
Here's an example:
pythonimport pandas as pd
# Read a CSV file
df = pd.read_csv('data.csv')
# Display the first 5 rows of the data
print(df.head())
In this example, data.csv
is the name of the file that we want to read. The read_csv()
function reads the file and stores it in a DataFrame, which is then displayed using the head()
function.
- Writing CSV files:
Once you have processed the data using Pandas, you may want to write it back to a CSV file. The to_csv()
function in Pandas is used to write data to a CSV file.
Here's an example:
pythonimport pandas as pd
# Create a DataFrame
data = {'Name': ['John', 'Mike', 'Sarah'], 'Age': [25, 30, 28]}
df = pd.DataFrame(data)
# Write the DataFrame to a CSV file
df.to_csv('output.csv', index=False)
This will write the data in the Pandas DataFrame to a CSV file named output.csv
3. Reading Excel files:
Pandas also provides a way to read Excel files using theread_excel()
function. For example:
kotlinimport pandas as pd
data = pd.read_excel('data.xlsx', sheet_name='Sheet1')
print(data)
This will read the Excel file.
4. Writing Excel files:
To write data to an Excel file using Pandas, you can use theto_excel()
function. For example:
kotlinimport pandas as pd
data = {'Name': ['John', 'Alice', 'Bob'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
df.to_excel('data.xlsx', index=False, sheet_name='Sheet1')
This will write the data in the Pandas DataFrame to an Excel file named data.xlsx
on Sheet1.
It's important to note that before reading or writing any file in Pandas, you need to ensure that the respective file format's libraries are installed. In the case of CSV and Excel files, you can use the pip install pandas
command to install the Pandas library, which includes support for these file formats.
Comments
Post a Comment