【问题标题】:Setting Values in Pandas Dataframe Based on Condition in Another Column根据另一列中的条件在 Pandas Dataframe 中设置值
【发布时间】:2021-07-07 14:47:38
【问题描述】:

我希望更新满足特定条件的熊猫系列中的值,并从另一列中获取相应的值。

具体来说,我想查看subcluster 列,如果值等于1,我希望记录更新为cluster 列中的对应值。

例如:

Cluster Subcluster
3 1
3 2
3 1
3 4
4 1
4 2

应该是这样的

Cluster Subcluster
3 3
3 2
3 3
3 4
4 4
4 2

我一直在尝试使用 apply 和 lambda 函数,但似乎无法使其正常工作。任何建议将不胜感激。谢谢!

【问题讨论】:

    标签: python pandas dataframe function


    【解决方案1】:

    你可以使用np.where:

    import numpy as np
    
    df['Subcluster'] = np.where(df['Subcluster'].eq(1), df['Cluster'], df['Subcluster'])
    

    输出:

        Cluster  Subcluster
    0         3           3
    1         3           2
    2         3           3
    3         3           4
    4         4           4
    5         4           2
    

    【讨论】:

      【解决方案2】:

      在你的情况下尝试mask

      df.Subcluster.mask(lambda x : x==1, df.Cluster,inplace=True)
      df
      Out[12]: 
         Cluster  Subcluster
      0        3           3
      1        3           2
      2        3           3
      3        3           4
      4        4           4
      5        4           2
      

      或者

      df.loc[df.Subcluster==1,'Subcluster'] = df['Cluster']
      

      【讨论】:

        【解决方案3】:

        您真正需要的只是将 .loc 与掩码一起使用(您实际上不需要创建掩码,您可以内联应用掩码)

        df = pd.DataFrame({'cluster':np.random.randint(0,10,10)
                            ,'subcluster':np.random.randint(0,3,10)}
                         )
        df.to_clipboard(sep=',')
        

        df此时

        ,cluster,subcluster
        0,8,0
        1,5,2
        2,6,2
        3,6,1
        4,8,0
        5,1,1
        6,0,0
        7,6,0
        8,1,0
        9,3,1
        

        创建并应用掩码(您可以在一行中完成所有操作)

        mask = df.subcluster == 1
        df.loc[mask,'subcluster'] = df.loc[mask,'cluster']
        df.to_clipboard(sep=',')
        

        最终输出:

        ,cluster,subcluster
        0,8,0
        1,5,2
        2,6,2
        3,6,6
        4,8,0
        5,1,1
        6,0,0
        7,6,0
        8,1,0
        9,3,3
        

        【讨论】:

          【解决方案4】:

          这是您无法编写的 lambda。在lamba 中,x 对应于索引,因此您可以使用它来引用列中的特定行。

          df['Subcluster'] = df.apply(lambda x: x['Cluster'] if x['Subcluster'] == 1 else x['Subcluster'], axis = 1)
          

          还有输出:

              Cluster Subcluster
          0   3       3
          1   3       2
          2   3       3
          3   3       4
          4   4       4
          5   4       2
          

          【讨论】:

            猜你喜欢
            • 2018-08-16
            • 1970-01-01
            • 1970-01-01
            • 2020-08-20
            • 2012-10-15
            • 1970-01-01
            • 2018-09-26
            • 1970-01-01
            相关资源
            最近更新 更多