1

I'm working on removing alphabet (a-z and A-Z), numbers and punctuations and left chinese characters only from v1 to v3 of the following dataframe.

    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 it works but it left some punctuations:

cols = ['v1', 'v2', 'v3']
df[cols] = df[cols].apply(lambda x: x.str.replace(r'[\x00-\x7F]+', ''))

Output:

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

How could I improve the code? Thanks.

ah bon
  • 9,293
  • 12
  • 65
  • 148

1 Answers1

1

you can use next regexp it collect only chinese characters:

cols = ['v1', 'v2', 'v3']
df[cols] = df[cols].apply(lambda x: x.str.replace(r'[^\u4e00-\u9FFF]+', ''))

if you want to keep whitespace you can add \s

cols = ['v1', 'v2', 'v3']
df[cols] = df[cols].apply(lambda x: x.str.replace(r'[^\u4e00-\u9FFF\s]+', ''))
alex2007v
  • 1,230
  • 8
  • 12
  • Sorry, it generates an error: `TypeError: ('expected string or bytes-like object', 'occurred at index v1')`. Does it works for you? – ah bon Feb 13 '20 at 07:48
  • 1
    There are way more Chinese characters than `\u4e00-\u9FFF`. See [this](https://stackoverflow.com/questions/1366068/whats-the-complete-range-for-chinese-characters-in-unicode) post for details. – Henry Yik Feb 13 '20 at 07:56
  • I still get `TypeError: ('expected string or bytes-like object', 'occurred at index v1')` – ah bon Feb 13 '20 at 07:59