如何在使用seaborn绘图时处理缺失值?

2024-09-29 02:23:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用lambda以下函数将缺少的值替换为NaN:

data = data.applymap(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)

,其中data是我正在处理的数据帧。

之后,我尝试使用seaborn绘制它的一个属性alccumption Using seaborn.distplot,如下所示:

seaborn.distplot(data['alcconsumption'],hist=True,bins=100)
plt.xlabel('AlcoholConsumption')
plt.ylabel('Frequency(normalized 0->1)')

它给了我以下错误:

AttributeError: max must be larger than min in range parameter.

Tags: andlambda函数dataifnppltseaborn
3条回答

可以使用以下行为使用seaborn的分布图选择非NaN值:

seaborn.distplot(data['alcconsumption'].notnull(),hist=True,bins=100)

我肯定会在绘制数据之前处理缺失的值。是否不使用dropna()完全取决于数据集的性质。alcconsumption是单个系列还是数据帧的一部分?在后一种情况下,使用dropna()也会删除其他列中的相应行。丢失的值是少还是多?它们是在你的系列中传播,还是倾向于在群体中出现?或许有理由相信你的数据集中有一个趋势?

如果缺少的值很少且分散,则可以很容易地使用dropna()。在其他情况下,我会选择用以前观察到的值(1)填充缺少的值。甚至用插值(2)填充缺失的值。但要小心!用填充或插值的观测值替换大量数据可能会严重中断数据集并导致非常错误的结论。

下面是一些使用你的代码片段的例子。。。

seaborn.distplot(data['alcconsumption'],hist=True,bins=100)
plt.xlabel('AlcoholConsumption')
plt.ylabel('Frequency(normalized 0->1)')

。。。在合成数据集上:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

def sample(rows, names):
    ''' Function to create data sample with random returns

    Parameters
    ==========
    rows : number of rows in the dataframe
    names: list of names to represent assets

    Example
    =======

    >>> sample(rows = 2, names = ['A', 'B'])

                  A       B
    2017-01-01  0.0027  0.0075
    2017-01-02 -0.0050 -0.0024
    '''
    listVars= names
    rng = pd.date_range('1/1/2017', periods=rows, freq='D')
    df_temp = pd.DataFrame(np.random.randint(-100,100,size=(rows, len(listVars))), columns=listVars) 
    df_temp = df_temp.set_index(rng)


    return df_temp

df = sample(rows = 15, names = ['A', 'B'])
df['A'][8:12] = np.nan
df

输出:

            A   B
2017-01-01 -63.0  10
2017-01-02  49.0  79
2017-01-03 -55.0  59
2017-01-04  89.0  34
2017-01-05 -13.0 -80
2017-01-06  36.0  90
2017-01-07 -41.0  86
2017-01-08  10.0 -81
2017-01-09   NaN -61
2017-01-10   NaN -80
2017-01-11   NaN -39
2017-01-12   NaN  24
2017-01-13 -73.0 -25
2017-01-14 -40.0  86
2017-01-15  97.0  60

(1)使用向前填充pandas.DataFrame.fillna(method = ffill)

ffill将“向前填充值”,这意味着它将用上面行的值替换nan

df = df['A'].fillna(axis=0, method='ffill')
sns.distplot(df, hist=True,bins=5)
plt.xlabel('AlcoholConsumption')
plt.ylabel('Frequency(normalized 0->1)')

enter image description here

(2)使用带pandas.DataFrame.interpolate()的插值

根据不同的方法插值。时间插值是对日数据和高分辨率数据进行插值,以插值给定的区间长度。

df['A'] = df['A'].interpolate(method = 'time')
sns.distplot(df['A'], hist=True,bins=5)
plt.xlabel('AlcoholConsumption')
plt.ylabel('Frequency(normalized 0->1)')

enter image description here

如您所见,不同的方法呈现两个截然不同的结果。我希望这对你有用。如果没有,请告诉我,我会再看一次。

这是matplotlib/pylab直方图的已知问题!

参见例如https://github.com/matplotlib/matplotlib/issues/6483

在建议各种解决方法的情况下,有两个最受欢迎的方法(例如https://stackoverflow.com/a/19090183/1021819)是:

import numpy as np
nbins=100
A=data['alcconsumption']
Anan=A[~np.isnan(A)] # Remove the NaNs

seaborn.distplot(Anan,hist=True,bins=nbins)

或者,指定bin边(在本例中,无论如何都要使用Anan…):

Amin=min(Anan)
Amax=max(Anan)
seaborn.distplot(A,hist=True,bins=np.linspace(Amin,Amax,nbins))

相关问题 更多 >