【问题标题】:Placing values in a separate column based on multiple row values根据多个行值将值放在单独的列中
【发布时间】:2020-06-29 23:30:40
【问题描述】:

我有下表:

Index Product       Start   End   2012   2013   2014   2015   2016  2017   2018   
0     product a     2015    2017  NaN    NaN    NaN    NaN    NaN   NaN    NaN    
1     product b     2008    2017  NaN    NaN    NaN    NaN    NaN   NaN    NaN    
2     product c     2012    2015  NaN    NaN    NaN    NaN    NaN   NaN    NaN    
3     product d     2033    2034  NaN    NaN    NaN    NaN    NaN   NaN    NaN    
4     product e     2014    2020  NaN    NaN    NaN    NaN    NaN   NaN    NaN    

我想把它转换成这个:

Index Product    Start End  2012      2013      2014      2015      2016      2017      2018    
0     product a  2015  2017 NaN       NaN       NaN       product a product a product a NaN     
1     product b  2008  2017 product b product b product b product b product b product b NaN     
2     product c  2012  2015 product c product c product c product c NaN       NaN       NaN     
3     product d  2033  2034 NaN       NaN       NaN       NaN       NaN       NaN       NaN     
4     product e  2014  2020 NaN       NaN       product e product e product e product e product e

因此,如果 Start 和 End 之间存在 2012-2018 列,则根据列名将产品放置在适当的单元格中。

我知道这是可能的,但我正在努力寻找解决方案。它是列名的组合,没有特定的值,而是一个范围,这让我很困惑。

我正在使用 python 数据框。

列名 2012-2018 表示年份的最后两位数字与周数相连接。所以 2020 年 3 月 18 日发生在 2020 年的第 12 周,所以它变成了 2012 年。

非常感谢任何帮助。

【问题讨论】:

    标签: python pandas dataframe jupyter-notebook


    【解决方案1】:

    我们可以做numpy广播然后分配回去

    s=df.columns[3:].astype(int).values[:,None]
    df.iloc[:,3:]=pd.DataFrame((df.Start.values<=s)&(s<=df.End.values)).T.mul(df.Product,0).values
    
    
    df
    Out[191]: 
            Product  Start   End      2012  ...      2015      2016      2017      2018
    Index                                   ...                                        
    0      producta   2015  2017            ...  producta  producta  producta          
    1      productb   2008  2017  productb  ...  productb  productb  productb          
    2      productc   2012  2015  productc  ...  productc                              
    3      productd   2033  2034            ...                                        
    4      producte   2014  2020            ...  producte  producte  producte  producte
    [5 rows x 10 columns]
    

    【讨论】:

    • 太棒了。正是我需要的。
    【解决方案2】:
    df=pd.melt(df, id_vars=['Product','Start','End'], value_vars=[2012, 2013, 2014, 2015, 2016, 2017, 2018])
    
    df['value']=np.where((df['variable']>=Start) &(df['variable']<=end), 'Product', df['value'])
    
    df=df.pivot_table(index=['Product','Start','End'], columns='variable', values='value')
    
    df_df.reset_index()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 2020-05-08
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多