【问题标题】:Transpose Dataframe with some Conditions [duplicate]在某些条件下转置 Dataframe [重复]
【发布时间】:2020-08-17 18:50:37
【问题描述】:

我有一个数据框,示例如下-

      UserId      UserName     Temp     Values       City     Country

 1    jsmith     James Smith     x        20        London     UK
 2    msmith     Michael Smith   y        25        Chicago    US
 3    mgarcia    Maria Garcia    z        60        Delhi      India

我想创建新的数据框,我想将 UserIDUserName 列保留在新数据框中,并且不希望列 Temp 和 From Values to Country 列 我想转置该列。我尝试了各种方法,但无法得到它。我需要像下面这样的最终输出-

      UserId      UserName      Values 

 1    jsmith     James Smith      20
 2    jsmith     James Smith    London
 3    jsmith     James Smith      UK
 4    msmith     Michael Smith    25
 5    msmith     Michael Smith  Chicago
 6    msmith     Michael Smith    US
 7    mgarcia    Maria Garcia     60
 8    mgarcia    Maria Garcia    Delhi
 9    mgarcia    Maria Garcia    India

如何做到这一点?

【问题讨论】:

    标签: python pandas numpy dataframe jupyter-notebook


    【解决方案1】:
    res = (df.set_index(['UserId','UserName'])
           .drop('Temp',axis=1)
           .stack()
           .droplevel(-1)
           .reset_index(name='Values')
          )
    
    res
    
        UserId  UserName    Values
    0   jsmith  James Smith 20
    1   jsmith  James Smith London
    2   jsmith  James Smith UK
    3   msmith  Michael Smith   25
    4   msmith  Michael Smith   Chicago
    5   msmith  Michael Smith   US
    6   mgarcia Maria Garcia    60
    7   mgarcia Maria Garcia    Delhi
    8   mgarcia Maria Garcia    India
    

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2023-03-21
      • 1970-01-01
      • 2020-10-26
      相关资源
      最近更新 更多