【问题标题】:How to copy value from one column to another based on conditions in pythons dataframe?如何根据python数据框中的条件将值从一列复制到另一列?
【发布时间】:2022-01-25 01:20:58
【问题描述】:

我有一个数据框 image of dataftrame

我需要将 teleport_value 复制到 value 列,仅适用于列 rule 的行是 'teleport' 且列 value 是 '' 的情况,在其他情况下是value 列将保持不变。

因此,数据框将如下所示: image of requested dataftrame

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    按照您在问题中描述的那样在列上写下条件,并将输出分配给value。 一种选择是在这种情况下使用numpy.where。请注意,还有许多其他方法可以实现相同的目标。

    import numpy as np
    import pandas as pd
    
    # You don't need this part of the code, I used it to recreate the 
    # dataframe, as you have shared a link to a screenshot..
    df = pd.DataFrame({
        'operator': np.array([[i] * 3 for i in ['First', 'Second', 'Third']]).flatten(),
        'solution': ['row'] * 9,
        'rule': ['allow', 'block', 'teleport'] * 3,
        'value': [1, 0, '', 0, 1, 'loc', 1, 1, ''],
        'teleport_value': ['', '', 'value'] + [''] * 5 + ['value']
    })
    
    
    # Solution: I have put the comments with your own words from question,
    # so that you know what does each line..
    df['value'] = np.where(
        (
            (df['rule'] == 'teleport') & # row with column rule is 'teleport' AND
            (df['value'] == '') # column value is ''
        ),
        df['teleport_value'], # copy teleport_value to value column
        df['value'] # in other cases the field of column value will be without changes
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2018-12-27
      • 2022-07-30
      • 2019-10-31
      相关资源
      最近更新 更多