0

Quite new to Python so apologies if there is an obvious fix to this. I'm working with some football data and the player names have come out like this:

https://i.stack.imgur.com/O9ffX.png

To remove everything after the "\" I tried:

head, sep, tail = df2["Player"].partition("\\")
head = df2["Player"]

To which I'm getting the following error:

"AttributeError: 'Series' object has no attribute 'partition'"

What am I doing wrong?

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • 2
    You can try `df2["Player"] = df2["Player"].str.split('\\').str[0]` – Shubham Sharma Feb 19 '21 at 15:53
  • Does this answer your question? [Apply pandas function to column to create multiple new columns?](https://stackoverflow.com/questions/16236684/apply-pandas-function-to-column-to-create-multiple-new-columns) – mayosten Feb 19 '21 at 15:54
  • To add to @ShubhamSharma's comment, you need to use the str accessor `df.column.str` to do string operations – Andy Feb 19 '21 at 15:55
  • I tried @ShubhamSharma's suggestion but got this: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead – SanthiCazorla Feb 19 '21 at 16:13
  • @Oso What do you mean? ShubhamSharma has included .str before the functions? – SanthiCazorla Feb 19 '21 at 16:14
  • @SanthiCazorla I was just adding exposition to the line of code, the key is the `.str` after the field. – Andy Feb 19 '21 at 16:15
  • @mayosten Unfortunately not, do not quite understand the code written here – SanthiCazorla Feb 19 '21 at 16:17
  • @Oso Please can you explain what you mean? Sorry very new to Python – SanthiCazorla Feb 19 '21 at 16:18
  • @SanthiCazorla i guess in this case you can safely ignore the warning. To read more about `SettingWithCopyWarning` check this [answer](https://stackoverflow.com/a/53954986/12833166) – Shubham Sharma Feb 19 '21 at 16:20
  • 1
    @SanthiCazorla if you want to use string functions on a pandas column, you specify that: `df.column.split()` won't work, but `df.column.str.split()` does because you're using the `str` accessor – Andy Feb 19 '21 at 16:23
  • 1
    @ShubhamSharma I will take a look at that, thank you! I realised it worked :) – SanthiCazorla Feb 19 '21 at 16:24
  • @SanthiCazorla happy coding :) – Shubham Sharma Feb 19 '21 at 16:25
  • @Oso Ok got you. Why do we need the ".str[0]" . Why can't it be: df2["Player"] = df2["Player"].str.split('\\')[0]? – SanthiCazorla Feb 19 '21 at 16:25
  • FYI, this will only work if all the names are capitalized. For example, if you have `\t` or `\n` Python will read that as a special character and will not split on it just using `str.split('\\')`. But if your names are all caps, should work – mayosten Feb 19 '21 at 16:30

0 Answers0