I have a dataframe. One of the columns is a combination of CITY
and STATE
. I want to split this column to two columns, CITY
and STATE
using:
df['CITY'],df['STATE'] = df['WORKSITE'].str.split(",")
And I got this error:
ValueError Traceback (most recent call last) in () ----> 1 df['CITY'],df['STATE'] = df['WORKSITE'].str.split(",")
ValueError: too many values to unpack (expected 2)
So, I'm wondering is there a method that I can ignore the exceptions or detect which row is not working?
Set n=2
in the split
call and use the str
method effectively:
import pandas as pd
x = ['New York, NY', 'Los Angeles, CA', 'Kansas City, KS, US']
df = pd.DataFrame(x, columns=['WORKSITE'])
df['CITY'], df['STATE'] = df['WORKSITE'].str.split(',', 2).str[0:2].str
print df
Output
WORKSITE CITY STATE
0 New York, NY New York NY
1 Los Angeles, CA Los Angeles CA
2 Kansas City, KS, US Kansas City KS
I got some help from looking at this answer to this question .
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.