根据另一列中的值将值追加到一列中 Python

问题描述 投票:0回答:1

我有两列,“Order_Category”和“Order_Status”,我想附加“Order_Category”列以反映以下内容:

'F': "- 填充" 'C':“- 已取消” 'R':“- 已拒绝”

我需要创建一个函数,该函数将迭代“Order_Status”列,并在状态等于“F”、“C”或“R”时附加“Order_Category”列,并在状态等于“O”或“X”时忽略'.

def get_status(order_stat):    
    categories = {
            
            'F': [" - Filled"],
            'C': [" - Cancelled"],
            'R': [" - Rejected"],
        }
python
1个回答
0
投票

以下是实现所需输出的方法:

  1. 定义一个带有两个参数的函数:一个用于订单状态,一个用于订单类别。
  2. 在函数内,使用循环或向量化操作来迭代状态。
  3. 检查状态并根据您提供的映射将相应的字符串附加到类别中。
  4. 确保该函数返回订单类别的更新列表(或系列,如果您使用 pandas)。
def update_order_category(order_statuses, order_categories):

    # Define the mapping as provided
    status_to_text = {
        'F': " - Filled",
        'C': " - Cancelled",
        'R': " - Rejected",
    }
    
    # Initialize an empty list to hold the updated categories
    updated_categories = []
    
    # Iterate through both lists simultaneously
    for status, category in zip(order_statuses, order_categories):
        # Check if the status has a corresponding update text
        if status in status_to_text:
            # Append the update text to the category
            category += status_to_text[status]

        # Add the updated category to the list
        updated_categories.append(category)
    
    return updated_categories


# Example usage:
order_statuses = ['F', 'C', 'R', 'O', 'X']
order_categories = ['Order1', 'Order2', 'Order3', 'Order4', 'Order5']
df = pd.DataFrame({'Order_Category': order_categories, 'Order_Status': order_statuses})


df["Order_Category"] = update_order_category(df['Order_Status'], df['Order_Category'])
df

输出:

上述解决方案返回以下内容

pandas.DataFrame

订单_类别 订单状态
0 订单 1 - 已完成 F
1 订单 2 - 已取消 C
2 订单 3 - 被拒绝 R
3 订单4 O
4 订单5 X
© www.soinside.com 2019 - 2024. All rights reserved.