Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to made a slice in a pandas dataframe?

I want do a slice a dataframe using a string "PP" that is in my column and get just the numbers that is afeter string:

Dataframe:

data = {'Serie':['28PP3097', '23228PP3097', '1822343218PP3097', '43642183097'],
    'FooBar':["foo", "bar", "foo", "bar"]}
df = pd.DataFrame(data)

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected Result:

enter image description here

I try:

df["Serie"] = np.where(df["Serie"].str.contains("PP"), df["Serie"][df["Serie"].str.find('PP')+1:],df["Serie"])

In this df, but it give me a erro ´cannot do slice indexing on RangeIndex with these indexers´

>Solution :

You can do that by splitting and getting the last item after "PP":

data = {'Serie':['28PP3097', '23228PP3097', '1822343218PP3097', '43642183097'],
        'FooBar':["foo", "bar", "foo", "bar"]}
df = pd.DataFrame(data)

df['Serie']=[i.split('PP')[-1] for i in df['Serie']]

Result

         Serie FooBar
0         3097    foo
1         3097    bar
2         3097    foo
3  43642183097    bar
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading