I'm trying to slice a column in dataframe in pandas

Viewed 58
Df['column']
123
567789476
900XXX444ABCJJJ863XXX
0
2748462838583627484
STITISTISTISTIXXXXXXXXXXXX
836XXX738JJJ484ZZZ838ZZZ
33
269EEHHJ
8888

I TRIED

Df['column']=Df['column'].str[:3]

Output

Nan
Nan
900
Nan
Nan
STI
836
Nan
269
Nan

I tried all possblie way to change the dtype of the column to string but it remains as object only

3 Answers

you can force the conversion to string before slicing it

 df['column'] = df['column'].apply(lambda : str(x)[:3])

This should work for you:

df['Column'].astype(str).str[:3]

You can see the result here when applied to your data:

In[7]: df['Column'].astype(str).str[:3]
Out[7]: 
0    123
1    567
2    900
3      0
4    274
5    STI
6    836
7     33
8    269
9    888

You can find more about astype in the documentation.

If you want to change the data type of a column in a Pandas Dataframe you can use as type . Here is the Documentation. Using your example: df["column"] = data["column"].astype(str) . Then, if you want to take only the first three letters or numbers of every row, you can make:

for i in list(range(len(df)):
     df.iloc[i][0][::3]

Let me know if you have further questions.

Related