Search code examples
pythondatabasedataframe

how to choose certain amount of characters from a column in Python?


for example, there is a column in a dataframe, 'ID'. One of the entries is for example, '13245993, 3004992' I only want to get '13245993'. That also applies for every row in column 'ID'. How to change the data in each row in column 'ID'?


Solution

  • You can try like this, apply slicing on ID column to get the required result. I am using 3 chars as no:of chars here

    
    import pandas as pd
    data = {'Name':['Tom', 'nick', 'krish', 'jack'],
            'ID':[90877, 10909, 12223, 12334]}
    df=pd.DataFrame(data)
    print('Before change')
    print(df)
    df["ID"]=df["ID"].apply(lambda x: (str(x)[:3]))
    print('After change')
    print(df)
    

    output

    Before change
    Name     ID
    0    Tom  90877
    1   nick  10909
    2  krish  12223
    3   jack  12334
    After change
    Name   ID
    0    Tom  908
    1   nick  109
    2  krish  122
    3   jack  123