1

I have this dataframe:

dict_values = {'name':['John','Peter'], 'attach':['0001-test.jpg,0002-test.jpg','0003-test.jpg']}
name | attach
John | 0001-test.jpg,0002-test.jpg
Peter | 0003-test.jpg

I need to get the value before "-" and append into a list.

Like this:

name | attach
John | [0001,0002]
Peter | [0003]

How I do this?

0

3 Answers 3

4

u can also use findall

dict_values = {'name':['John','Peter'], 
               'attach':['0001-test.jpg,0002-test.jpg','0003-test.jpg']}

df = pd.DataFrame(dict_values)
df['attach'] = df['attach'].str.findall("(\d+)-")

output,

    name        attach
0   John  [0001, 0002]
1  Peter        [0003]
Sign up to request clarification or add additional context in comments.

Comments

2

You can use extractall:

df = pd.DataFrame(dict_values)
df['attach'] = (df.attach.str.extractall('(\d*)-')[0]
                   .groupby(level=0).agg(list)
                )

Output:

    name        attach
0   John  [0001, 0002]
1  Peter        [0003]

Comments

0

IIUC, lets use explode and agg

df = pd.DataFrame(dict_values)

df1 = df.set_index("name")["attach"].str.split(
    ",").explode().str.split("-", expand=True)[0]\
        .groupby(level=0).agg(list)

print(df1)

name
John     [0001, 0002]
Peter          [0003]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.