Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to work on the below code:

import pandas as pd

a=pd.Series([123,22,32,453,45,453,56])

b=pd.Series([234,4353,355,453,345,453,56])

df=pd.concat([a, b], axis=1)

df.columns=['First', 'Second']

I wanted to add a new column to this data frame with the first digit from values in column 'First': a) change number to string from column 'First' b) extracting the first character from newly created string c) The results from b save as new column in the data frame

I don't know how to apply this to the pandas' data frame object. I would be grateful for helping me with that.

1 Answer

0 votes
by (36.8k points)

Cast the dtype of the col to str, and then perform vectorized slicing calling str:

In [29]:

df['new_col'] = df['First'].astype(str).str[0]

df

Out[29]:

   First  Second new_col

0    123     234       1

1     22    4353       2

2     32     355       3

3    453     453       4

4     45     345       4

5    453     453       4

6     56      56       5

if you need to you can cast the dtype back again calling astype(int) on the column

Improve your knowledge in data science from scratch using Data science online courses

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...