在python中熔化不完整的数据而不丢弃所有NaN

我正在尝试使用pd.melt将3列熔化为一个分类列.目前,数据框看起来像这样.

    id1   Plane  Car   Boat
0   123   None   None  None
1   124   Plane  None  None
2   125   None   None  Boat

在某些时候,我用NaN代替None,但我不确定在融化前是否有必要.我的目标是有一个类别列,列出它的车辆类型,仅当所有列都为空时才使用None.

    id1   Type
0   123   None   
1   124   Plane  
2   125   Boat   

我想出的代码是这样的:

df = pd.melt(df, id_vars=['id1'], var_name='Type')

我遇到的问题是它使我的数据框中的观察结果增加了三倍.我可以过滤掉Type = None的行,但是会丢弃诸如id1 = 123之类的数据,其中所有三个原始列都是None.

    id1   Type
0   123   None   
1   123   None  
2   123   None  
3   124   Plane
4   124   None   
5   124   None  

有没有一种有效的方法来解决熔化问题?或者我是否需要遍历数据并使用条件写入新的数据帧?

最佳答案 你这样做.使用reindex来获取那些缺少的id值.

df1 = df.replace('None',np.nan).set_index('id1')
df1.stack().reset_index(level=1, drop=True).reindex(df1.index)

输出:

id1
123      NaN
124    Plane
125     Boat
dtype: object
点赞