简体   繁体   中英

How to add 91 to all the values in a column of a pandas data frame?

Consider my data frame as like this

S.no Phone Number
1 9955290232
2 8752837492
3 9342832245
4 919485928837
5 917482482938
6 98273642733

I want the values in "Phone number" column to prefixed with 91 If the value has 91 already then, proceed to the next value.

My output

S.no Phone Number
1 919955290232
2 918752837492
3 919342832245
4 919485928837
5 917482482938
6 919827364273

How could this be done?

Simplest would be comvert to string, add 91 to the beginning and slice to last 12 digits:

df['New Phone Number'] = df['Phone Number'].astype(str).radd("91").str[-12:]

Series.str.replace

df['Phone Number'].astype(str).str.replace(r'^(?!91)', '91')

0     919955290232
1     918752837492
2     919342832245
3     919485928837
4     917482482938
5    9198273642733
Name: Phone Number, dtype: object

With your shown samples, you could try following code. This makes sure that it catches 10 digits phone numbers only(valid by number of digits).

df['Phone Number'].astype(str).replace({r'^(?!91)(\d{10})$' : r'91\1'}, regex=True)

Online demo for above regex

Simple explanation would be: changing DataFrame's Phone Number column's value to string and using replace to check if its not starting from 91 and followed by 10 digits then add 91 to it.

You can apply() on each element in Series.

def add(x):
    if '91' in str(x):
        return str(x)
    else:
        return '91'+str(x)

df['Phone Number'] = df['Phone Number'].apply(add)

Or with lambda in one line

df['Phone Number'] = df['Phone Number'].apply(lambda x: str(x) if '91' in str(x) else '91' + str(x) )

You can also do this by boolean masking astype() method and startswith() method:

mask=df['Phone Number'].astype(str).str.startswith('91')

Finally use:

df.loc[~mask,'Phone Number']='91'+df.loc[~mask,'Phone Number'].astype(str)

Now If you print df you will get:

0     919955290232
1     918752837492
2     919342832245
3     919485928837
4     917482482938
5     9198273642733
Name: Phone Number, dtype: object

You can try this out....one of way to do it where df is your dataframe name

def add_91(x):
    return '91'+str(x)

df['Phone Number'] = df['Phone Number'].apply(lambda x:add_91(x))

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