【问题标题】:Use a list to conditionally fill a new column based on values in multiple columns使用列表根据多列中的值有条件地填充新列
【发布时间】:2023-03-21 04:40:01
【问题描述】:

我正在尝试通过使用多个列中的值来填充 pandas 数据框中的新列。原始列是0 或“1”,每个系列只有一个1。通过填充new_col = [1, 3, 7, 10],新列将对应于 df['A','B','C','D'],如下所示。 (1A 表示new_col = 1;如果B=1new_col = 3 等)

df    
         A    B    C    D
1        1    0    0    0
2        0    0    1    0
3        0    0    0    1
4        0    1    0    0

新的df 应该是这样的。

df    
         A    B    C    D   new_col
1        1    0    0    0         1
2        0    0    1    0         7
3        0    0    0    1        10
4        0    1    0    0         3

我尝试使用maplocwhere,但似乎无法制定有效的方法来完成它。问题似乎非常接近to this。我看过的其他几篇帖子123。这些都没有显示如何根据列表有条件地使用多列来填充新列。

【问题讨论】:

    标签: python list python-2.7 pandas


    【解决方案1】:

    我可以想到几种方法,主要涉及 argmaxidxmax,以获得我们可以用来填充列的 ndarray 或 Series。

    我们可以下拉到numpy,找到最大位置(1 所在的位置)并使用它们来索引 new_col 的数组版本:

    In [148]: np.take(new_col,np.argmax(df.values,1))
    Out[148]: array([ 1,  7, 10,  3])
    

    我们可以创建一个以 new_col 为值、列为索引的 Series,并使用 idxmax 对其进行索引:

    In [116]: pd.Series(new_col, index=df.columns).loc[df.idxmax(1)].values
    Out[116]: array([ 1,  7, 10,  3])
    

    我们可以使用 get_indexer 将列 idxmax 结果转换为我们可以与 new_col 一起使用的整数偏移量:

    In [117]: np.array(new_col)[df.columns.get_indexer(df.idxmax(axis=1))]
    Out[117]: array([ 1,  7, 10,  3])
    

    或者(这似乎很浪费)我们可以用新列创建一个新框架并直接使用 idxmax:

    In [118]: pd.DataFrame(df.values, columns=new_col).idxmax(1)
    Out[118]: 
    0     1
    1     7
    2    10
    3     3
    dtype: int64
    

    【讨论】:

      【解决方案2】:

      这不是最优雅的解决方案,但对我来说它胜过 if/elif/elif 循环:

      d = {'A': 1, 'B': 3, 'C': 7, 'D': 10}
      def new_col(row):
          k = row[row == 1].index.tolist()[0]
          return d[k]
      
      df['new_col'] = df.apply(new_col, axis=1)
      

      输出:

          A   B   C   D   new_col
      1   1   0   0   0   1
      2   0   0   1   0   7
      3   0   0   0   1   10
      4   0   1   0   0   3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-29
        • 2013-02-12
        • 1970-01-01
        • 1970-01-01
        • 2022-11-30
        • 2017-01-08
        相关资源
        最近更新 更多