我有两列,“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"],
}
以下是实现所需输出的方法:
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 |