Pandas 是 Python 中一个非常流行的数据分析库,它提供了强大的数据结构和数据分析工具,可以轻松处理和分析结构化数据。
安装 Pandas
首先,确保你已经安装了 Python。然后,你可以使用 pip 来安装 Pandas:
pip install pandas
基础使用
Pandas 中的 DataFrame 是一个表格型的数据结构,类似于 Excel 表格。下面是一个简单的例子:
import pandas as pd
data = {'Name': ['Tom', 'Nick', 'John', 'Alice'],
'Age': [20, 21, 19, 18],
'City': ['New York', 'London', 'Paris', 'Berlin']}
df = pd.DataFrame(data)
print(df)
输出:
Name | Age | City |
---|---|---|
Tom | 20 | New York |
Nick | 21 | London |
John | 19 | Paris |
Alice | 18 | Berlin |
选择数据
你可以使用 .loc
和 .iloc
方法来选择 DataFrame 中的数据。
# 选择行
print(df.loc[0])
# 选择列
print(df['Name'])
# 选择行和列
print(df.loc[0, 'Name'])
数据清洗
Pandas 提供了多种数据清洗功能,例如去除重复数据、填充缺失值等。
# 去除重复数据
df.drop_duplicates(inplace=True)
# 填充缺失值
df.fillna('Unknown', inplace=True)
数据操作
Pandas 提供了丰富的数据操作功能,例如排序、筛选等。
# 排序
df.sort_values(by='Age', ascending=False, inplace=True)
# 筛选
print(df[df['Age'] > 20])
数据可视化
Pandas 可以与 Matplotlib、Seaborn 等库结合使用进行数据可视化。
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.plot(df['Age'], df['City'])
plt.title('Age vs City')
plt.xlabel('Age')
plt.ylabel('City')
plt.show()
Age vs City
更多 Pandas 教程,请访问 Pandas 官方文档