【问题标题】:Please help me with the following pandas data frame manipulation请帮助我进行以下熊猫数据框操作
【发布时间】:2021-10-03 20:35:12
【问题描述】:

我有一个如下的数据框: `

`pd.DataFrame({
            'location':['Hyd','Mum','Viz'],
            'rank1':[1,2,3],
            'rank2':[np.NaN,1,2],
})

看起来像这样:

    location    rank1   rank2
0   Hyd         1       NaN
1   Mum         2       1
2   Viz         3       2

现在我想添加一列“来源”,使其如下所示

    location    rank1   rank2   source
0   Hyd         1       NaN     Mum
1   Mum         2       1       Viz
2   Viz         3       2       none

正如您在上面第一列中看到的那样,我们得到了 Mum,因为第一行中的 rank1 = 1 = 第二行中的 rank2,其位置为 Mum,因此我们将 mum 分配给第一列中的源,其他列也相同 请帮帮我 谢谢

【问题讨论】:

    标签: python-3.x pandas dataframe sorting


    【解决方案1】:

    下面的代码应该可以工作,因为它是rank,假设它是一个唯一值,那么'Source'列的最后一行必然有'nan'。

    # let x be the dataframe
    import pandas as pd
    import numpy as np
    
    x=pd.DataFrame({
                'location':['Hyd','Mum','Viz'],
                'rank1':[1,2,3],
                'rank2':[np.NaN,1,2],
    })
    
    # Make an empty list of source
    source=[]
    
    # Loop over the 'rank1'
    for i in x['rank1']:
      # for every i in rank1
      # find the index of row with i in rank2
      # (yes, index will be very next one,
      #  provided that the data is sorted) 
      try:
        source.append(x['location'][list(x['rank2']).index(i)])
      # as the last value in rank1 
      # will not be present in rank2
      # catch this error and append with nan
      except:
        source.append(np.NaN)
    
    # once source list is ready,
    # make a new column and fill these values
    
    x['Source']=source
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 2011-09-14
      • 2020-12-27
      • 2016-08-28
      相关资源
      最近更新 更多