2

If I do: Series.str.split("/") on a Pandas Series that has names like "A/American black duck/Illinois/4119/2009", then I get back a Pandas Series that has a list like:

[A, American black duck, Illinois, 4119, 2009]

in each row.

The state name (Illinois, for example) is what I would like to assign as a new column in a separate DataFrame. Is there some way to do something like the following?

newdf['State'] = Series.str.split("/")[2]

(For the record, I've already tried that, but it returns an error.)

ericmjl
  • 13,541
  • 12
  • 51
  • 80
  • 1
    I think this is a dup of [this question](http://stackoverflow.com/questions/12504976/get-last-column-after-str-split-operation-on-column-in-pandas-dataframe]): Wes' answer for your situation would be `s.str.split("/").str[2]`, and is better than mine. – DSM Jun 13 '14 at 21:21
  • 2
    DSM is correct that would work, also this works also: `df.col.str.split('/')[0][2]` but I prefer DSM's – EdChum Jun 13 '14 at 21:24
  • 1
    The technical reason is that what `split` returns is another pandas series, it will have a single row with index value `0` and an NDArray of values, this is why you get a `KeyError` doing `Series.str.split("/")[2]`, you may be confused by the IPython output which looks like it is a list but it is not. Calling the method `str` on `split` again allows you to access the individual values – EdChum Jun 13 '14 at 21:28
  • Wonderful, I did remember seeing that other question, but I couldn't find the right keywords to search for it. Would you all recommend that I delete my question? – ericmjl Jun 13 '14 at 21:42
  • 1
    I think not, I will vote to close as duplicate and over time it should get enough votes and be linked to that question – EdChum Jun 13 '14 at 21:55
  • Ditto here. Thanks guys! – ericmjl Jun 13 '14 at 22:00
  • @DSM Ooooh, we can insta-close duplicate questions now! Wes' solution is concise/quite surprising... (@ericmjl Duplicate questions redirect on google searches for non-logged in users, so you're helping other people find the correct search in the future! +1) – Andy Hayden Jun 14 '14 at 05:10

0 Answers0