Why does Pandas complain about 'n' being an invalid keyword argument for the split function?

Viewed 79

I'm trying to split a string with a full name into first and last names. And because some last names here consist of several words, I'm trying to use the parameter 'n' to limit the number of splits.

When I'm trying this code:

name = df.loc[28,'name'].split()

It works. For example, it splits "Jan van den Berg" into "Jan, van, den, Berg". But I need "Jan, van den Berg". So I'm trying to use the parameter 'n' to limit the number of splits, as explained in this guide. (That guide is strictly speaking for series, but I found that it works for dataframes as well as long as I don't use paramters.)

But that's where my issue starts: According to that guide, I should be able to use this code, and it should only split the string once:

name = df.loc[28,'name'].split(n=1)

But it doesn't. It gives me the following error message:

"'n' is an invalid keyword argument for split()"

So what am I missing? Does the split function only work for dataframes as long as you don't use paramters? Because it looks like I'm using the exact same code as the example, yet it refuses to work.

1 Answers

df.loc[28,'name'] returns a string (not a DataFrame, not a Series).

Python string split() method does not have an n argument. It has an equivalent maxsplit argument.

So, you might either perform a Pandas str method on a Series like:

df['name'].str.split(n = 1)

Or use Python str method like:

df.loc[28,'name'].split(maxsplit = 1)
Related