简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM