Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Columns in pandas with str.split and keep values

So I am stuck with a problem here:

I have a pandas dataframe which looks like the following:

ID Name    Value
0  Peter   21,2
1  Frank   24
2  Tom     23,21/23,60 
3  Ismael  21,2/ 21,54
4  Joe     23,1

and so on...

What I am trying to is to split the "Value" column by the slash forward (/) but keep all the values, which do not have this kind of pattern.

Like here:

ID Name    Value
0  Peter   21,2
1  Frank   24
2  Tom     23,21
3  Ismael  21,2
4  Joe     23,1

How can I achieve this? I tried the str.split method but it's not giving me the solution I want. Instead, it returns NaN as can be seen in the following.

My Code: df['Value']=df['value'].str.split('/', expand=True)[0]

Returns:

ID Name    Value
0  Peter   NaN
1  Frank   NaN
2  Tom     23,21
3  Ismael  21,2
4  Joe     Nan

All I need is the very first Value before the '/' is coming.

Appreciate any kind of help!

like image 891
lazer Avatar asked Sep 08 '26 04:09

lazer


1 Answers

Remove expand=True for return lists and add str[0] for select first value:

df['Value'] = df['Value'].str.split('/').str[0]
print (df)
   ID    Name  Value
0   0   Peter   21,2
1   1   Frank     24
2   2     Tom  23,21
3   3  Ismael   21,2
4   4     Joe   23,1

If performance is important use list comprehension:

df['Value'] = [x.split('/')[0] for x in df['Value']]
like image 135
jezrael Avatar answered Sep 10 '26 18:09

jezrael