Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

python - How to split Dataframe column into two parts and replace column with splitted value

How can I split a dataframe column into two parts such that the value in dataframe column is later replaced by the splitted value. For example, I have a dataframe like :

col1       col2
"abc"      "A, BC"
"def"      "AX, Z"
"pqr"      "P, R"
"xyz"      "X, YZ"

I want to extract values before , and replace that cell with the extracted value. So, the output should look like :

col1   col2
abc    A
def    AX
pqr    P
xyz    X

I am trying to do it as :

df['col2'].apply(lambda x: x.split(',')[0])

But it gives me error. Please suggest how can I get the desired output.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In this case you can you the str methods of pandas, that will use vectorized functions. It will also be faster that apply.

df.col2 = df.col2.str.split(', ').str[0]

>>> df
Out[]:
  col1 col2
0  abc    A
1  def   AX
2  pqr    P
3  xyz    X

To use this on Series containing string, you should call the str attribute before any function. See the doc for more details.

In the above solution, note the .str.split(', ') that replace split. And .str[0] that allow to slice the result of the split, whereas just using .str.split(', ')[0] would get index 0 of the Series.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...