pandas bring data from one df to another issue

前端 未结 1 1506
鱼传尺愫
鱼传尺愫 2021-01-26 07:15

I have a data set that has a count of duplicates:

#Count number of injuries by levels for each players
levelcount = df.gro         


        
相关标签:
1条回答
  • 2021-01-26 07:59

    Use Series.map with dictionary for new column, append to index by DataFrame.set_index and reshape by Series.unstack:

    levelcount = df.groupby(['Relinquished','Severity']).size().reset_index(name='count')
    d = {1:'DTD',2:'DNP',3:'outindefinitely',4:'outforseason'}
    
    new = levelcount.set_index(levelcount['Severity'].map(d), append=True)['Count'].unstack()
    levelcount = levelcount.join(new.reindex(list(d.values()), axis=1))
    print (levelcount)
      Relinquished  Severity  Count  DTD  DNP  outindefinitely  outforseason
    0      player1         1      1  1.0  NaN              NaN           NaN
    1      player1         3      1  NaN  NaN              1.0           NaN
    2      player2         3      1  NaN  NaN              1.0           NaN
    3      player3         1      3  3.0  NaN              NaN           NaN
    

    Your solution is possible by loop by dictionary and set new columns:

    levelcount = df.groupby(['Relinquished','Severity']).size().reset_index(name='count')
    d = {1:'DTD',2:'DNP',3:'outindefinitely',4:'outforseason'}
    
    for k, v in d.items():
        levecount = levelcount.loc[levelcount['Severity'] == k, v] = levelcount['count']
    
    0 讨论(0)
提交回复
热议问题