Reputation: 137
So I was wondering how can I split the strinf column into 2 columns, but not after I come across first comma, but second.
data = pd.DataFrame({ 'Address': ["Berlin, 842, 05", "Vienna, 810, 00", "Moscow, 820, 00"]})
data[["city", "code"]] = data["Address"].str.split(",", n= 2, expand = True)
data
So I would want something like
City Code
Berlin, 842 05
Vienna, 810 00
Moscow, 820 00
Upvotes: 1
Views: 530
Reputation: 260975
n
denotes the number of splits, not the number of output columns. You should use n=1
. Also, use rsplit
:
data[['city', 'code']] = data['Address'].str.rsplit(',', n=1, expand=True)
output:
Address city code
0 Mojkovac,842, 05 Mojkovac, 842 05
1 Podgorica,810, 00 Podgorica, 810 00
2 Kolasin,820, 00 Kolasin, 820 00
If you further want to remove the comma in city
data['city'] = data['city'].str.replace(',', '')
Upvotes: 2