python - 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
我正在尝试根据这些标准添加一个值;
- 如果
make == netgear
(设置为 0) - 如果 switch 后的值为 20 或更大(设置为 1,否则设置为 0)
(如果两个条件都满足,则设置为 0,即“make == netgear
设置为 0”的条件优先。请注意,这与现有代码不同,如果两个条件都满足,则第二个条件覆盖(和覆盖结果值)。)
我最初得到了一些帮助,但是有些设备现在有一个-new
and p
or a
or 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)
这在一些命名的末尾添加新内容之前效果很好,现在它显然中断了。我已经尝试了各种方法,但我找不到一个体面的方法来忽略-new
and p
or a
ore
编辑
对不起,我完全搞砸了我想问的问题,我试图根据 after 的值来做值'switch'
。
本质上使用现有代码将字符串转换为整数并len
落在任何具有-new
andp
或a
ore
其后的名称上
例如说
ValueError:int() 的无效文字,基数为 10:'switch23-new'
解决方案
您可以使用.loc
and 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
推荐阅读
- django - 我的 django 服务器的 import_export 模块在导入时不起作用
- d3.js - 如何停止 d3.histogram() 修剪前导和尾随空箱
- sql - Hive 查找表填充空值
- go - 从管道中的先前命令读取退出状态
- linux - 从 Docker 访问 Linux 内核加密 API
- javascript - 使用angularjs表达式在jquery中设置html
- haskell - 如何在 Haskell 中将此函数从 exceptT 转换为 except?
- python - 使用字典作为另一个字典的键?
- php - 使用 Symfony 和 Monolog 的 Slack 通知
- assembly - 汇编语言 - 查找数组中的最大数