Python:如何向直方图添加过滤器

问题描述 投票:0回答:1

我在 Power BI 中使用 Python,目前有以下代码:

import matplotlib.pyplot as plt
plt.hist(dataset.age, bins=10, edgecolor="#6A9662", color="#DDFFDD", alpha=0.75)
plt.show()

在我的表格中,我有一列带有“E”和“G”的类型。如何将 Filter TYPE = "E" 添加到 Python 代码中?

提前非常感谢!

我希望我的直方图仅显示过滤表 TYPE =“E”的结果。

python powerbi filtering histogram
1个回答
0
投票

您可以在将数据输入到 hist 函数之前对其进行过滤。例如,如果您的原始数据集驻留在包含

Name    Age Type
Car1    1   E
Car2    5   G
Car3    9   G
Car4    2   E
Car5    8   E
Car6    6   G
Car7    9   E
Car8    3   G
Car9    5   G
Car10   7   G
Car11   2   E

您可以使用以下代码进行处理:

import matplotlib.pyplot as plt
import pandas as pd


# read data from the CSV file
dataset = pd.read_csv('dataset.csv', delimiter='\t')

# filter type E data
dataset_type_e = dataset[dataset["Type"] == "E"]

plt.hist(dataset_type_e["Age"], bins=10, edgecolor="#6A9662", color="#DDFFDD", alpha=0.75)
plt.show()

这就是我得到的结果:

© www.soinside.com 2019 - 2024. All rights reserved.