gpt4 book ai didi

python - 基于 str.find 的 Pandas 切片字符串作为开始和停止的位置

转载 作者:行者123 更新时间:2023-12-04 13:32:51 25 4
gpt4 key购买 nike

我有一个看起来像这样的数据框

commands
*client interface : Eth-Trunk45.2903 is up
*client interface : Eth-Trunk46.2620 is up
*client interface : Eth-Trunk46.2988 is up
*client interface : Eth-Trunk55.1703 is up
*client interface : Eth-Trunk55.1704 is up
*client interface : GigabitEthernet4/1/12.102 is up
如何切片字符串并获得如下输出。
commands
Eth-Trunk45.2903
Eth-Trunk46.2620
Eth-Trunk46.2988
Eth-Trunk55.1703
Eth-Trunk55.1704
GigabitEthernet4/1/12.102
我试试
df['commands'] = df['commands'].str.slice(start=df['commands'].str.find(':'), stop=df['commands'].str.find(' is'))
但这只会返回我的 nan 值。
请帮忙。

最佳答案

使用 Series.str.extract 获取值之间的值:

df['commands'] = df['commands'].str.extract(r":(.+) is", expand=False)
print (df)
commands
0 Eth-Trunk45.2903
1 Eth-Trunk46.2620
2 Eth-Trunk46.2988
3 Eth-Trunk55.1703
4 Eth-Trunk55.1704
5 GigabitEthernet4/1/12.102
您的解决方案可以在 Series.apply ,因为 Pandas 切片只对所有列使用相同的整数:
df['commands'] = df['commands'].apply(lambda x: x[x.find(': ') + 1: x.find(' is ')])
print (df)
commands
0 Eth-Trunk45.2903
1 Eth-Trunk46.2620
2 Eth-Trunk46.2988
3 Eth-Trunk55.1703
4 Eth-Trunk55.1704
5 GigabitEthernet4/1/12.102
print (df['commands'].str.slice(26, 42))
0 Eth-Trunk45.2903
1 Eth-Trunk46.2620
2 Eth-Trunk46.2988
3 Eth-Trunk55.1703
4 Eth-Trunk55.1704
5 GigabitEthernet4
Name: commands, dtype: object

关于python - 基于 str.find 的 Pandas 切片字符串作为开始和停止的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64040560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com