Breaking string from a character

Asked

Viewed 374 times

0

Inside my dataframe, one of the columns has information separated by comma, I would like to delete everything within the string after the first comma.

Follow the code I’m trying to use:

df_movies = df_movies[df_movies["country"].str.split(",")]

I’m getting the following error code:

TypeError: unhashable type: 'list'

2 answers

3

The code you tried doesn’t make sense.

df_movies = df_movies[df_movies["country"].str.split(",")]

You seek the string that has comma separated values and separates the values in that character. That is, if you receive the string 'a,b,c' you will build the list ['a', 'b', 'c'].

After that you try to access the dataframe from that list, which would be basically:

df_movies[['a', 'b', 'c']]

What should it do?

If the idea is to fetch the first value before the comma, you do not need to access again the dataframe. Just define the value mapping logic and apply it to your column:

df_movies['country'] = df_movies['country'].apply(
    lambda values: values.split(',')[0]
)

Thus, the column 'country' shall have only the first name of the list.

  • That’s exactly what I wanted! Thank you very much

0

When you use .split it transforms the string into an array separated by the character you used. in this case I think I could do so:

In [6]: minha_string = "antesdavirgula,depoisdavirgula"                                                                                                                                                            

In [7]: antes_da_virgula, *_ = minha_string.split(",")[0]                                                                                                                                                              

In [8]: antes_da_virgula                                                                                                                                                                                           
Out[8]: 'antesdavirgula'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.