Imagine I have:
COLUMN A
0 00000-UNITED STATES
1 01000-ALABAMA
2 01001-Autauga County, AL
3 01003-Baldwin County, AL
4 Barbour County, AL
I want to split them in two columns but making sure that if the value in the last row is a string, it goes to the second column. If it's an int it goes to the first column. Eg with string:
COLUMN B COLUMN C
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 Barbour County, AL
I tried this:
df[['B','C']] = df.A.str.split(" - ", n = 1, expand=True)
And it returned this obviously:
COLUMN B COLUMN C
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 Barbour County, AL
Try with extract
and a regex to have the second capture group be the value after the optional -
:
df[['B', 'C']] = df['A'].str.extract(r"(\d+$|\d+(?=\s*-))?(?:\s*-\s*)?(.+)?")
A B C
0 00000-UNITED STATES 00000 UNITED STATES
1 01000-ALABAMA 01000 ALABAMA
2 01001-Autauga County, AL 01001 Autauga County, AL
3 01003-Baldwin County, AL 01003 Baldwin County, AL
4 Barbour County, AL NaN Barbour County, AL
5 10234 10234 NaN
6 32 Alabama NaN 32 Alabama
7 432423 - state 432423 state
Complete Code:
import pandas as pd
df = pd.DataFrame({
'A': ['00000-UNITED STATES', '01000-ALABAMA',
'01001-Autauga County, AL', '01003-Baldwin County, AL',
'Barbour County, AL', '10234', '32 Alabama', '432423 - state']
})
df[['B', 'C']] = df['A'].str.extract(r"(\d+$|\d+(?=\s*-))?(?:\s*-\s*)?(.+)?")
You could create two functions to extract the desired elements from COLUMN A and assign to COLUMN B and COLUMN C:
def get_col_b(item):
if '-' in item:
return item.split('-')[0]
else:
return ''
def get_col_c(item):
if '-' in item:
return item.split('-')[1]
else:
return item
Create the columns and then drop COLUMN A:
df['COLUMN B'] = df['COLUMN A'].apply(get_col_b)
df['COLUMN C'] = df['COLUMN A'].apply(get_col_c)
cols = ['COLUMN B', 'COLUMN C']
df = df[cols]
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.