Bob Haffner
Bob Haffner

Reputation: 8483

Using a function while slicing

Looking for some clarification and some direction here

--Given a simple Pandas data frame

df = pd.DataFrame(['123abc','456xyz'],columns=['foo'])

foo

0   123abc

1   456xyz

--This works

df.foo.str[:3]

0    123

1    456

--This does not

df.foo.str[:df.foo.str.len()]

0   NaN

1   NaN

Upvotes: 0

Views: 35

Answers (1)

EdChum
EdChum

Reputation: 394031

If you are just wanting to extract just the numbers from the strings then you can use extract:

In [23]:

df = pd.DataFrame(['123abc','45xyz'],columns=['foo'])
df.foo.str.findall(r'\d+').str[0]

Out[23]:
0    123
1     45
Name: foo, dtype: object

If you just want to slice from beginning of the string up to the last 3 characters then you can use a negative offset:

In [25]:

df = pd.DataFrame(['123abc','45xyz'],columns=['foo'])
df.foo.str[:-3]

Out[25]:
0    123
1     45
Name: foo, dtype: object

Upvotes: 1

Related Questions