Home > OS >  how to choose certain amount of character from a column in Python?
how to choose certain amount of character from a column in Python?

Time:10-18

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'?

CodePudding user response:

You could do something like

data[data['ID'] == '13245993']

this will give you the columns where ID is 13245993

More Indepth Code

I hope this answers your question if not please let me know.

With best regards

CodePudding user response:

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
  • Related