【问题标题】:Dataframe pivot, lining up new column values without create additional NaN values数据框透视,排列新列值而不创建额外的 NaN 值
【发布时间】:2020-11-08 20:27:22
【问题描述】:

所以我试图从制表符分隔的文本文件创建一个数据框,目的是使用数据框列标题中的一列中的值,并使用第二列作为值。当我尝试 df.pivot 时,我得到了我想要的,但是新列添加了额外的 NaN 值,而不是仅仅将新行正确排列。

制表符分隔的文本文件基本上是这样的:

round1    are you healthy   no
round1    are you healthy   yes
round2    are you healthy   yes
round2    are you healthy   yes
round3    are you healthy   no
round3    are you healthy   yes

所以我有这个:

 import pandas as pd
    import numpy as np
    df = pd.read_csv('test.txt', sep='\t', usecols=[0,2], names=['colA','colB'])
    df = df.pivot(index=None,columns='colA',values='colB')
    print(df)

这给了我这个:

colA round1 round2 round3
0        no    NaN    NaN
1       yes    NaN    NaN
2       NaN    yes    NaN
3       NaN    yes    NaN
4       NaN    NaN     no
5       NaN    NaN    yes

但我想要实现的是:

colA round1 round2 round3
0        no    yes    no
1       yes    yes    yes

【问题讨论】:

    标签: python pandas dataframe pivot-table


    【解决方案1】:

    请尝试

    df2=df.iloc[:,1:]#Filter out ColA because its basically the index
    df2[:]=np.sort(df2.fillna('z').values, axis=0)#Convert NaN to z
    df2[df2!='z'].dropna(0)filter not wanted
    
    
    
      round1 round2 round3
    0     no    yes     no
    1    yes    yes    yes
    

    或者

    df1=df.iloc[:,1:].replace({'yes':1,'no':0}).fillna(-1)#Convert to integers temporarily to allow soring
    df1[:]=np.sort(df1.values, axis=0)#Sort dataframe
    df1[df1!=-1].dropna(0).astype(bool).replace({True: 'yes',False:'no'})#drop unwanted and replace values to original
    
    
     round1 round2 round3
    4     no    yes     no
    5    yes    yes    yes
    

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 2022-08-12
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 2018-03-26
      • 2021-10-03
      相关资源
      最近更新 更多