【问题标题】:replace values in pandas based on other two column根据其他两列替换熊猫中的值
【发布时间】:2018-04-26 06:25:10
【问题描述】:

我对其他两列条件列中的替换值有疑问。

例如,我们有三列。 A、B 和 C A 列和 B 列都是布尔值,包含 True 和 False,C 列包含三个值:“Payroll”、“Social”和“Other”。

当 A 列和 B 列在 C 列中为真时,我们有值“工资单”。 我想更改 A 列和 B 列都为 True 的 C 列中的值。

我尝试了以下代码:但给了我这个错误“'NoneType'对象没有属性'where'”:

data1.replace({'C' : { 'Payroll', 'Social'}},inplace=True).where((data1['A'] == True) & (data1['B'] == True))

但是给了我这个错误“'NoneType'对象没有属性'where'”:

有什么办法可以解决这个问题?

【问题讨论】:

    标签: python-3.x pandas dataframe replace


    【解决方案1】:

    我认为您需要all 来检查每行是否所有Trues,然后通过布尔掩码过滤DataFrame 分配输出:

    data1 = pd.DataFrame({
        'C': ['Payroll','Other','Payroll','Social'],
        'A': [True, True, True, False],
        'B':[False, True, True, False]
    })
    print (data1)
           A      B        C
    0   True  False  Payroll
    1   True   True    Other
    2   True   True  Payroll
    3  False  False   Social
    
    m = data1[['A', 'B']].all(axis=1)
    #same output as
    #m = data1['A'] & data1['B']
    print (m)
    0    False
    1     True
    2     True
    3    False
    dtype: bool
    
    print (data1[m])
          A     B        C
    1  True  True    Other
    2  True  True  Payroll
    

    data1[m] = data1[m].replace({'C' : { 'Payroll':'Social'}})
    print (data1)
           A      B        C
    0   True  False  Payroll
    1   True   True    Other
    2   True   True   Social
    3  False  False   Social
    

    【讨论】:

    • 好的,但是A列和B列必须满足的条件在哪里?
    • 隐藏在all,但也可以使用m = data1['A'] & data1['B']
    • #jezrael,在这个条件替换之后,我需要将它导出到 excel 文件中,是否会有原始列 C,其中的值已经更改?
    • 所以只需要将第 2 行从示例导出到 excel 吗?
    • 不,我想导出整个数据框,并在 C 列中进行更改。有可能吗?
    【解决方案2】:

    你可以使用apply函数来做到这一点

    def change_value(dataframe):
       for index, row in df.iterrows():
          if row['A'] == row['B'] == True:
               row['C'] = # Change to whatever value you want
          else:
               row ['C'] = # Change how ever you want
    

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 2023-01-26
      • 1970-01-01
      • 2018-10-15
      • 2022-06-15
      • 2018-01-10
      • 1970-01-01
      • 2021-02-20
      • 2018-11-06
      相关资源
      最近更新 更多