[英]Pandas string slice returns NaN
I have a dataframe as below:我有一个如下的数据框:
Ref Net
C1 1- A:VCC
C2 2- A:VDD
C3 3- A:GND
I would like to remove 1- A:
, 2- A:
and 3- A:
from the Net
column:我想从Net
列中删除1- A:
、 2- A:
和3- A:
:
Ref Net
C1 VCC
C2 VDD
C3 GND
I tried this command: df.Net = df.Net.str.slice(df.Net.str.find('A:'))
我试过这个命令: df.Net = df.Net.str.slice(df.Net.str.find('A:'))
But then the Net
column became NaN
:但随后Net
列变成了NaN
:
print(df.Net)
---------
0 NaN
1 NaN
2 NaN
The slice command returns the proper values: slice 命令返回正确的值:
print(df.Net.str.find('A:'))
------
0 3
1 3
2 3
What did I miss here?我在这里错过了什么?
I assume, net Series has type str.我假设,net 系列的类型为 str。 Perhaps you should try something like :也许您应该尝试以下操作:
df['result'] = df['Net'].apply(str).apply(lambda x: x.split(':')[-1])
apply(str)
is optional if type is str.如果 type 是 str, apply(str)
是可选的。
You can do this:你可以这样做:
In [539]: df.Net = df.Net.str.split(':').str[-1]
In [540]: df
Out[540]:
Ref Net
0 C1 VCC
1 C2 VDD
2 C3 GND
You can use regex for this您可以为此使用正则表达式
import pandas as pd
df = pd.DataFrame({'Ref':['C1', 'C2'], 'Net':['1- A:VCC', '2- A:VDD']})
df['Net'] = df['Net'].str.replace(r'\d- \w:', '')
Output:输出:
Ref Net
0 C1 VCC
1 C2 VDD
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.