Home > Software design >  AttributeError: 'tuple' object has no attribute 'slice' in using pandas
AttributeError: 'tuple' object has no attribute 'slice' in using pandas

Time:12-10

I have column title (genre). I try to get first element by using many way slicing split and try to using another method but I have this message:

for x in df['genres']:
    c = tuple(x).slice(0, x.find('|'))
    print (c)

AttributeError: 'tuple' object has no attribute 'slice'

genre has values like this (Action|Adventure|Science Fiction|Thriller) for ten thousand rows.

CodePudding user response:

You don't need to use a tuple for this.

Try this:

for x in df['genres']:
    c = x.split('|')[0]
    print(c)

CodePudding user response:

tuple just doesn't have slice. Try using pandas.Series.str.split instead:

# Sample data
                                              genres
0      Thriller|Action|Adventure|Adventure|Adventure
1  Science Fiction|Adventure|Science Fiction|Adve...
2  Science Fiction|Thriller|Science Fiction|Thril...
3  Adventure|Thriller|Science Fiction|Action|Thri...
4        Action|Adventure|Adventure|Adventure|Action

df["genres"].str.split("|").str[0]

Output:

0           Thriller
1    Science Fiction
2    Science Fiction
3          Adventure
4             Action
Name: genres, dtype: object

Explain:

  • df["genres"].str.split("|"): splits each element in df["genres"] with the given sep. This will yield lists of separated items in each row.
  • str[0]: selects the first item of lists from each row.
  • Related