![](/img/trans.png)
[英]using pandas str.find method to slice strings in dataframe column
[英]Pandas slice string based on str.find as position to start and stop
我有一個看起來像這樣的數據框
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
是可能的,因為熊貓切片僅對所有列使用相同的整數:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.