TransWikia.com

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

Stack Overflow Asked on December 25, 2021

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

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.

Answered by Dennis Concepción Martín on December 25, 2021

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.

Answered by Gamopo on December 25, 2021

you can force the conversion to string before slicing it

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

Answered by Hicham Zouarhi on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP