Skip to main content
  1. About
  2. For Teams
Asked
Viewed 98 times
2
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
  • why nan in output, why not 123 as I see 900, how you splitting
    Akhilesh_IN
    –  Akhilesh_IN
    2020-07-24 08:18:01 +00:00
    Commented Jul 24, 2020 at 8:18
  • 1
    @Akhilesh_IN because 123 is stored as a number, while 900XXX444ABCJJJ863XXX is a string
    Gamopo
    –  Gamopo
    2020-07-24 08:21:08 +00:00
    Commented Jul 24, 2020 at 8:21
  • Correct @Akhilesh
    user11675397
    –  user11675397
    2020-07-24 09:22:15 +00:00
    Commented Jul 24, 2020 at 9:22

3 Answers 3

1

you can force the conversion to string before slicing it

 df['column'] = df['column'].apply(lambda : str(x)[:3])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.