emax
emax

Reputation: 7255

Not apply the same function to all rows of a Pandas column?

I want to extact the first 3 from values of a pandas column without doing a loop.

So,

df['myCol'][3]
5475

In order to extract the first 3 digits I do:

int(str(df['myCol'][3])[:2])
547

I want to apply to all the same procedure to the entire column. How can I do it?

Upvotes: 3

Views: 53

Answers (3)

zipa
zipa

Reputation: 27879

If you like playing with format this one also does the job:

df['myCol'].map(lambda x: '{:.3}'.format(str(x)))

Upvotes: 1

jezrael
jezrael

Reputation: 863226

I think need select by indexing with str[] and then cast to integers:

df['myCol'].str[:2].astype(int)

If input values are integers, first cast to strings:

df['myCol'].astype(str).str[:2].astype(int)

Upvotes: 2

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210902

assuming you have a numeric column:

In [189]: df
Out[189]:
    myCol
0    5475
1   99999
2  123456

In [190]: df.dtypes
Out[190]:
myCol    int64
dtype: object

In [191]: df['myCol'] // 10**(np.log10(df.myCol).astype(int) - 2)
Out[191]:
0    547
1    999
2    123
Name: myCol, dtype: int64

Upvotes: 2

Related Questions