Home > Software design >  extracts a given number of characters from the left side of string paramater
extracts a given number of characters from the left side of string paramater

Time:01-24

I have an ID paramater in pandas df .

df['id']

I want to keep only the 4 first characters from the left side(like left function in excel).

for example

54354832 > 5435

CodePudding user response:

Try this:

df["ID"]=df.loc[:,"ID"].str[0:4]

Example:

df = pd.DataFrame({"ID": ["abcdefg", "abcdefg", "abcdefg"], "b": ["abcdefg", "abcdefg", "abcdefg"]})
df["ID"]=df.loc[:,"ID"].str[0:4]
  •  Tags:  
  • Related