简体   繁体   English

如何遍历两个 pandas 列并创建一个新列

[英]How to iterate through two pandas columns and create a new column

I am trying to create a new column by concatenating two columns with certain conditions.我正在尝试通过连接具有特定条件的两列来创建一个新列。

master['work_action'] = np.nan
for a,b in zip(master['repair_location'],master['work_service']):
    if a == 'Field':
        master['work_action'].append(a + " " + b)
    elif a == 'Depot':
        master['work_action'].append(a + " " + b)
    else:
        master['work_action'].append(a)

TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

The problem is with master['work_action'].append(a + " " + b)问题出在master['work_action'].append(a + " " + b)

If I change my code to this:如果我将代码更改为此:

test = []
for a,b in zip(master['repair_location'],master['work_service']):
    if a == 'Field':
        test.append(a + " " + b)
    elif a == 'Depot':
        test.append(a + " " + b)
    else:
        test.append(a)

I get exactly what I want in a list.我在列表中得到了我想要的东西。 But I want it in a pandas column.但我希望它在 pandas 列中。 How do I create a new pandas column with the conditions above?如何在上述条件下创建新的 pandas 列?

If performance is important, I would use numpy 's select :如果性能很重要,我会使用numpyselect

master = pd.DataFrame(
    {
        'repair_location': ['Field', 'Depot', 'Other'],
        'work_service':[1, 2, 3]
    }
)

master['work_action'] = np.select(
    condlist= [
        master['repair_location'] == 'Field',
        master['repair_location'] == 'Depot'
    ],
    choicelist= [
        master['repair_location'] + ' ' + master['work_service'].astype(str),
        master['repair_location'] + ' ' + master['work_service'].astype(str)
    ],
    default= master['repair_location']
)

Which results in:结果是:

  repair_location  work_service work_action
0           Field             1     Field 1
1           Depot             2     Depot 2
2           Other             3       Other

Append method is for insert values at the end. Append 方法用于在末尾插入值。 You are trying to concatenate two strings values.您正在尝试连接两个字符串值。 Use apply method:使用apply方法:

def fun(a,b):
    if a == 'Field':
        return a + " " + b
    elif a == 'Depot':
        return a + " " + b
    else:
       return a

master['work_action'] = master.apply(lambda x: fun(x['repair_location'], x['work_service']), axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM