首页 > 解决方案 > Pandas:创建新列并根据字符串列中的值(子字符串)和另一列中的值添加值

问题描述

如果这是一个重复的问题,我很抱歉,在我觉得我不得不发布一个问题之前,我确实四处寻找。

我正在尝试devicevalue根据另外 2 列的值在新列中分配一个值。我的数据框看起来有点像这样;

devicename           make     devicevalue
switch1               cisco        0
switch1-web100        netgear      0  
switch10              cisco        0
switch23              cisco        1
switch31-web200       netgear      0
switch31              cisco        1
switch41-new          cisco        1
switch40e             cisco        1
switch31-web200-new   netgear      0
switch40e             cisco        1
switch11-data100e     netgear      0

我正在尝试根据这些标准添加一个值;

(如果两个条件都满足,则设置为 0,即make == netgear设置为 0”的条件优先。请注意,这与现有代码不同,如果两个条件都满足,则第二个条件覆盖(和覆盖结果值)。)

我最初得到了一些帮助,但是有些设备现在有一个-newand por aor e,它破坏了在字符串末尾查看数字的代码

我使用的代码本质上是;

def get_number_suffix(devicename: str) -> int:
    i = 1
    while i < len(devicename) and devicename[-i:].isnumeric():
        i += 1

    return int(devicename[-(i-1):])


def compute_devicevalue(row) -> int:
    if 'netgear' in row['make']:
        return 0
    if 20 <= get_number_suffix(row['devicename']):
        return 1
    else:
        return 0

df['devicevalue'] = df.apply(compute_devicevalue, axis=1)

这在一些命名的末尾添加新内容之前效果很好,现在它显然中断了。我已经尝试了各种方法,但我找不到一个体面的方法来忽略-newand por aore

编辑

对不起,我完全搞砸了我想问的问题,我试图根据 after 的值来做值'switch'

本质上使用现有代码将字符串转换为整数并len落在任何具有-newandpaore其后的名称上

例如说

ValueError:int() 的无效文字,基数为 10:'switch23-new'

标签: pythonpython-3.xpandascsv

解决方案


您可以使用.locand str.extract(),如下所示:

df['devicevalue'] = 0     # init value to 0

# Set to 1 if the value after 'switch' >= 20. 
# Otherwise part is set during init to 0 at the first statement
df.loc[df['devicename'].str.extract(r'switch(\d+)', expand=False).astype(float) >= 20, 'devicevalue'] = 1

# Set to 0 if `make` == 'netgear'
df.loc[df['make'] == 'netgear', 'devicevalue'] = 0 
# If you have 2 or more values of `make` to match, use, e.g.:
#df.loc[df['make'].isin(['netgear', 'dell']), 'devicevalue'] = 0

正则表达式r'switch(\d+)'str.extract()提取数字一起使用,'switch'无论它们是在末尾还是在中间。因此,它解决了您之前在末尾的数字现在在中间的问题。

结果:

             devicename     make  devicevalue
0               switch1    cisco            0
1        switch1-web100  netgear            0
2              switch10    cisco            0
3              switch23    cisco            1
4       switch31-web200  netgear            0
5              switch31    cisco            1
6          switch41-new    cisco            1
7             switch40e    cisco            1
8   switch31-web200-new  netgear            0
9             switch40e    cisco            1
10    switch11-data100e  netgear            0

推荐阅读