ah bon
ah bon

Reputation: 10051

Split multiple columns by numeric or alphabetic symbols

I'm working on splitting multiple columns by numeric or alphabetic symbols for columns v1 to v3, then take the first part as the values of this column. For example, 红岗花园12栋110房 will be split by 12 then take 红岗花园, 德福花园德福豪苑C4栋C5栋C4座1403房 will be splited by C4 and take 德福花园德福豪苑.

    id       v1                      v2                     v3
0    1      泥岗路             红岗花园12栋110房                    NaN
1    2     沙井街道                     万丰路                     东侧
2    3      中心区                    N15区          幸福·海岸10栋A座11A
3    4      龙岗镇                     南联村       长海雅园2栋D301D302房产
4    5    蛇口工业区                     兴华路  海滨花园多层海滨花园兰山楼06栋504房产
5    6      宝安路         松园·南九巷综合楼10栋103                    NaN
6    7      宝安路         松园·南九巷综合楼10栋203                    NaN
7    8      龙岗镇                     中心城            尚景华园12栋307房
8    9     沙河西路            西博海名苑1栋30C房产                    NaN
9   10  华侨城香山中路              天鹅堡三期P栋4D房                    NaN
10  11      布吉镇  德福花园德福豪苑C4栋C5栋C4座1403房                    NaN

The code I have tried:

cols = ['v1', 'v2', 'v3']
df[cols] = df[cols].apply(lambda x: ''.join(re.compile(r'(\d+|\w+)')[0], x.str))

Output:

TypeError: ("'_sre.SRE_Pattern' object is not subscriptable", 'occurred at index v1')

My desired output will like this:

    id       v1         v2             v3
0    1      泥岗路       红岗花园            NaN
1    2     沙井街道        万丰路             东侧
2    3      中心区        NaN          幸福·海岸
3    4      龙岗镇        南联村           长海雅园
4    5    蛇口工业区        兴华路  海滨花园多层海滨花园兰山楼
5    6      宝安路  松园·南九巷综合楼            NaN
6    7      宝安路  松园·南九巷综合楼            NaN
7    8      龙岗镇        中心城           尚景华园
8    9     沙河西路      西博海名苑            NaN
9   10  华侨城香山中路      天鹅堡三期            NaN
10  11      布吉镇   德福花园德福豪苑            NaN

Thanks for your help.

Upvotes: 1

Views: 100

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

You may remove all text after the first ASCII alphanumeric character in the columns you need to modify:

cols = ['v1', 'v2', 'v3']
df[cols] = df[cols].apply(lambda x: x.str.replace(r'[A-Za-z0-9].*', ''))

If your columns can contain multiline texts, use

r'(?s)[A-Za-z0-9].*'

where (?s) inline modifier will let . match line break chars, too.

Upvotes: 2

Related Questions