根据另一列的值在一列中追加值 Python
我有两列数据,分别是“订单类别(Order_Category)”和“订单状态(Order_Status)”。我想要在“订单类别”这一列中添加一些内容,具体如下:
当状态是 'F' 时,添加 " - 已完成";
当状态是 'C' 时,添加 " - 已取消";
当状态是 'R' 时,添加 " - 已拒绝"。
我需要创建一个函数,这个函数会遍历“订单状态”这一列,当状态是 'F'、'C' 或 'R' 时,就在“订单类别”这一列后面添加相应的内容;如果状态是 'O' 或 'X',就不做任何处理。
def get_status(order_stat):
categories = {
'F': [" - Filled"],
'C': [" - Cancelled"],
'R': [" - Rejected"],
}
1 个回答
0
下面是实现你想要的输出的方法:
- 先定义一个函数,这个函数需要两个参数:一个是订单状态,另一个是订单类别。
- 在函数内部,使用一个循环或者一种叫做向量化操作的方法来遍历这些状态。
- 检查每个状态,然后根据你提供的映射,把对应的字符串添加到类别中。
- 确保这个函数能返回更新后的订单类别列表(如果你在用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 |