如何基于多个条件在df中创建新列?使用Pandas

2024-06-26 00:29:20 发布

您现在位置:Python中文网/ 问答频道 /正文

在这里,我需要在其他列中创建新列

样本数据:

colum1       column2

M           online

L           offline

C           online

L           online

H           online

M           online

L           offline

C           online

L           offline

这里我需要创建一个新的列

第1列=‘M’和;colum2=‘在线’——>;三天

第1列=‘M’和;colum2=“脱机”->;5天

像这样,我需要创建新的列

尝试了下面的代码,但我错过了逻辑

sales['Shipment Tat'] = np.where ((sales['Order Priority'] == 'M') & (sales['Sales Channel'] == 'Online') ,  'with in 9 days' )

预期产量

column1    column2       column3

M           online     3 days

M           offline    5 days

L           offline    5 days

C           online     7 days

L           online     7 days

H           online     9 days

H           offline    11 days    

Tags: 数据代码gt逻辑daysonline样本sales
1条回答
网友
1楼 · 发布于 2024-06-26 00:29:20

您可以使用apply方法-

def myFunc(record):
    if record['column1'] == 'M':
       if record'column2'] == 'online':
          return '3days'
       elif record['column2'] == 'offline':
          return '5days'
    return 'with in 9 days'

df['new_col'] = df.apply(myFunc, axis=1)

相关问题 更多 >