Reputation: 7255
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
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
Reputation: 863226
I think need select by indexing with str[]
and then cast to integer
s:
df['myCol'].str[:2].astype(int)
If input values are integers, first cast to string
s:
df['myCol'].astype(str).str[:2].astype(int)
Upvotes: 2
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