【问题标题】:Pandas - Create a column (col C) with values from another (col A) if a condition in another column (col B) is observedPandas - 如果观察到另一列 (col B) 中的条件,则使用来自另一列 (col A) 的值创建一列 (col C)
【发布时间】:2020-05-11 09:59:39
【问题描述】:

我有一个 DataFrame,正如我们在表 A 中看到的那样,它有两列。 A 列上的值是从 1 开始的 int。B 列中的值是二进制的。

我需要创建 C 列(表 B),其中: 如果 B 列上的值为 1,则获取相应行的 A 列上的值, 否则,如果 B 列上的值为 0,则相应行的 C 列将为 0。

示例 表A:

+---+---+
| A | B |
+---+---+
| 6 |  1|
| 10|  0|
| 50|  0|
|100|  1|
| 5 |  1|
| 2 |  0|
+---+---+

表 B:

+---+---+---+
| A | B | C |
+---+---+---+
| 6 |  1| 6 |
| 10|  0| 0 |
| 50|  0| 0 |
|100|  1|100|
| 5 |  1| 5 |
| 2 |  0| 0 |
+---+---+---|

代码:

# create df
import pandas as pd
d = {'A': [6,10,50,100,5,2], 'B': [1,0,0,1,1,0]}
dfA = pd.DataFrame(data=d) 
dfA

有人可以帮帮我吗?谢谢! :)

【问题讨论】:

    标签: python python-3.x pandas sklearn-pandas


    【解决方案1】:
    dfA['C']=0
    dfA.loc[dfA['B']==1, 'C'] = dfA['A']
    dfA
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值
    【解决方案2】:

    感谢您提供的极简工作示例!

    我会这样解决:

    dfA['C'] = dfA['A']          # copy A to C
    dfA['C'][dfA['B'] == 0] = 0  # set all positions in C where B is 0 to 0
    

    生成的dfA

         A  B    C
    0    6  1    6
    1   10  0    0
    2   50  0    0
    3  100  1  100
    4    5  1    5
    5    2  0    0
    

    【讨论】:

      【解决方案3】:

      numpy where clause 中,第一个参数是条件,下一个参数是“then”部分,然后“else”是列表

      import numpy as np
      df['C'] = np.where(df['B']==1, df['B'], 0)    
      

      【讨论】:

        【解决方案4】:

        如果 B 列是 0 或 1,您可以在 axis=1 上使用 prod 将 A 和 B 列多个列

        dfA['C'] = dfA.prod(axis=1)
        #dfA['C'] = dfA[['A','B']].prod(axis=1) if you have more columns
        print(dfA)
        

             A  B    C
        0    6  1    6
        1   10  0    0
        2   50  0    0
        3  100  1  100
        4    5  1    5
        5    2  0    0
        

        【讨论】:

          猜你喜欢
          • 2019-06-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-21
          相关资源
          最近更新 更多