简体   繁体   中英

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)

在此处输入图像描述

Expected Result:

在此处输入图像描述

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´

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

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