简体   繁体   中英

Categorize the dataframe column data into Latin/Non-Latin

I'm trying to categorize latin/non-latin data through Python. I want the output to be 'columnname: Latin' if it's Latin, 'columnname: Non-Latin' if it's non-latin. Here's the data set I'm using:

name|company|address|ssn|creditcardnumber

Gauge J. Wiley|Crown Holdings|1916 Central Park Columbus|697-01-963|4175-0049-9703-9147

Dalia G. Valenzuela|Urs Corporation|8672 Cottage|Cincinnati|056-74-804|3653-0049-5620-71

هاها|Exide Technologies|هاها|Washington|139-09-346|6495-1799-7338-6619

I tried adding the below code. I don't get any error, but I get 'Latin' all the time. Is there any issue with the code?

if any(dataset.name.astype(str).str.contains(u'[U+0000-U+007F]')):
    print ('Latin')
else:
    print('Non-Latin')

And also I'd be happy if someone could tell me how to display the output as "column name: Latin", column name being iterated from dataframe

It depends what need - if check if any value has non latin values or all values have strings with numpy.where :

df = pd.DataFrame({'name':[u"هاها",'a',u"aهاها"]})

#https://stackoverflow.com/a/3308844
import unicodedata as ud
latin_letters= {}
def is_latin(uchr):
    try: return latin_letters[uchr]
    except KeyError:
         return latin_letters.setdefault(uchr, 'LATIN' in ud.name(uchr))

def only_roman_chars(unistr):
    return all(is_latin(uchr)
           for uchr in unistr
           if uchr.isalpha()) 

#check if any
df['new1'] = np.where(df['name'].map(only_roman_chars), 'Latin','Non-Latin')
#check if all
df['new2'] = np.where(df.name.str.contains('[a-zA-Z]'), 'Latin','Non-Latin')
print (df)

    name       new1       new2
0   هاها  Non-Latin  Non-Latin
1      a      Latin      Latin
2  aهاها  Non-Latin      Latin

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM