欢迎访问宙启技术站
智能推送

如何在Python中使用Pandas.DataFrame进行数据可视化和探索

发布时间:2023-12-17 03:20:15

在Python中使用Pandas.DataFrame进行数据可视化和探索非常方便,以下是一些示例来说明如何使用Pandas.DataFrame进行数据可视化和探索。

首先,我们需要导入Pandas和Matplotlib库:

import pandas as pd
import matplotlib.pyplot as plt

然后,我们可以创建一个DataFrame对象,用于存储和操作我们的数据:

data = {'name': ['Tom', 'Nick', 'John', 'Sam'],
        'age': [21, 25, 18, 27],
        'income': [50000, 60000, 30000, 70000]}
df = pd.DataFrame(data)

接下来,我们可以使用不同的方法来探索和可视化数据:

1. 查看数据的前几行:

print(df.head())

输出:

  name  age  income
0  Tom   21   50000
1  Nick  25   60000
2  John  18   30000
3  Sam   27   70000

2. 查看数据的统计摘要:

print(df.describe())

输出:

             age        income
count   4.000000      4.000000
mean    22.750000  52500.000000
std      3.304038  16431.638761
min     18.000000  30000.000000
25%     20.250000  45000.000000
50%     23.000000  55000.000000
75%     25.500000  62500.000000
max     27.000000  70000.000000

3. 绘制柱状图来显示收入数据:

df.plot(x='name', y='income', kind='bar')
plt.ylabel('Income')
plt.title('Income distribution')
plt.show()

输出:

![bar_chart](https://user-images.githubusercontent.com/57796392/123562850-96324600-d7f3-11eb-9b85-b23faa8e0b92.png)

4. 绘制散点图来显示年龄和收入之间的关系:

df.plot(x='age', y='income', kind='scatter')
plt.xlabel('Age')
plt.ylabel('Income')
plt.title('Age vs. Income')
plt.show()

输出:

![scatter_plot](https://user-images.githubusercontent.com/57796392/123562873-af3af700-d7f3-11eb-8160-046ed5f1d9a3.png)

5. 绘制盒图来显示收入数据的分布:

df.plot(y='income', kind='box')
plt.ylabel('Income')
plt.title('Income distribution')
plt.show()

输出:

![box_plot](https://user-images.githubusercontent.com/57796392/123562893-cfd21f80-d7f3-11eb-9194-6e057f7675db.png)

通过使用Pandas.DataFrame,我们可以方便地对数据进行可视化和探索。这些示例涵盖了一些基本的数据可视化和探索方法,但在实际使用中,根据数据类型和问题的不同,我们可以使用更多的方法和图表类型来可视化和探索数据。