首页 > 解决方案 > 忽略无效数据的 Pandas 直方图;限制 x 范围

问题描述

我有一个数据框,其中包含文本和数字数据的混合,其中一些值-999表示丢失或无效数据。作为一个玩具示例,假设它看起来像这样:

import pandas as pd
import matplotlib.pyplot as plt

dictOne = {'Name':['First', 'Second', 'Third', 'Fourth', 'Fifth', 'Sixth', 'Seventh', 'Eighth', 'Ninth'],
           "A":[1, 2, -3, 4, 5, -999, 7, -999, 9],
           "B":[4, 5, 6, 5, 3, -999, 2, 9, 5],
           "C":[7, -999, 10, 5, 8, 6, 8, 2, 4]}
df2 = pd.DataFrame(dictOne)

df2.hist('C', bins = 1000)
plt.xlim=([0, 10])

这给 在此处输入图像描述

我试图排除这些-999值。Pandas 有没有简单的方法来做到这一点?

另外,在我的示例代码中,为什么 x 轴不限于 [0,10] 范围?

标签: pythonpandashistogram

解决方案


Instead of bins=1000, you can specify

df2.hist('C', bins=range(0,10))

Or if you want to align the histogram boxes in the middle:

df2.hist('C', bins=np.arange(0.5,11,1))

Output:

enter image description here


推荐阅读