【问题标题】:How to use the pandas.melt() while keeping the NaN values?如何在保持 NaN 值的同时使用 pandas.melt()?
【发布时间】:2019-07-12 04:18:21
【问题描述】:

我正在清理一个杂乱无章的数据框,其中一些需要的信息出现在列名中。此信息应融合到将要创建的单个列中。

index    name       animal    fruit    veg
--------------------------------------------------
0        cow        animal    NaN      NaN
1        apple      NaN       fruit    NaN
2        carrot     NaN       NaN      veg
3        dog        animal    NaN      NaN
4        horse      animal    NaN      NaN
5        car        NaN       NaN      NaN
6        pear       NaN       fruit    NaN
7        pepper     NaN       NaN      veg
8        cucumber   NaN       NaN      veg
9        house      NaN       NaN      NaN

我尝试过使用pandas.melt() 函数,但是它返回了很多带有“错误”NaN 值和重复值的行。

有些行应该显示NaN,但只有那些不适合列名中指定的类别的行,所以我不能使用pandas.dropna()

我也不能确定删除重复项不会删除重要数据。

这是我使用的代码:

import pandas as pd

pd.melt(df, id_vars=['index', 'name'],
        value_vars=['animal', 'fruit', 'veg'],
        var_name='type')

我需要的结果应该是这样的:

index    name       type
--------------------------------------------------
0        cow        animal
1        apple      fruit
2        carrot     veg
3        dog        animal
4        horse      animal
5        car        NaN
6        pear       fruit
7        pepper     veg
8        cucumber   veg
9        house      NaN

【问题讨论】:

    标签: python pandas dataframe data-cleaning


    【解决方案1】:

    您可以这样做(假设索引不是列,而是索引),在axis=1 上使用df.ffill()

    df['type']=df[df.columns[1:]].ffill(axis=1).iloc[:,-1]
    #alternatively-> df['type']=df.loc[:,['animal','fruit','veg']].ffill(axis=1).iloc[:,-1]
    df_new=df[['name','type']]
    print(df_new)
    
               name    type
    index                  
    0           cow  animal
    1         apple   fruit
    2        carrot     veg
    3           dog  animal
    4         horse  animal
    5           car     NaN
    6          pear   fruit
    7        pepper     veg
    8      cucumber     veg
    9         house     NaN
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-12
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2014-10-05
      • 1970-01-01
      相关资源
      最近更新 更多