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
Solution 1:
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
1defAX2 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
.
Post a Comment for "How To Split Dataframe Column Into Two Parts And Replace Column With Splitted Value"