简体   繁体   中英

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:

Ref   Net  
C1    VCC  
C2    VDD  
C3    GND  

I tried this command: df.Net = df.Net.str.slice(df.Net.str.find('A:'))

But then the Net column became NaN :

print(df.Net)
---------
0  NaN
1  NaN
2  NaN

The slice command returns the proper values:

print(df.Net.str.find('A:'))
------
0  3
1  3
2  3

What did I miss here?

I assume, net Series has type 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.

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:', '')

  Ref    Net
0  C1  VCC
1  C2  VDD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM