Getting the first item of a split string list in a Pandas series

Viewed 1430

If I need to split a string and get the first item, that's fine with:

string = "AAA_BBB"
string.split("_")[0]
> "AAA"

But if try to do the same with a Pandas series (given the series has the same string format), the [0] doesn't work.

df["string"].str.split("_")[0]
> KeyError: 0

But the part before the [0] works fine

1 [AAA, BBB]
2 [BBB, CCC]
3 [DDD, EEE]
4 [DDD, AAA]
5 [EEE, CCC]

I'm trying to do this to assign the first element to a new column like so:

df["new_column"] = df["string"].str.split("_")[0]
0 Answers
Related