0
print(df["date"].str.replace("2016","16"))

The code above works fine. What I really want to do is to make this replacement in just a small part of the data-frame. Something like:

df.loc[2:4,["date"]].str.replace("2016","16")

However here I get an error:

AttributeError: 'DataFrame' object has no attribute 'str'
2
  • 4
    Try removing the brackets from around "date". Passing a single column label as a list in .loc forces a dataframe to return. If you just pass a single label as a scalar you will return a pd.Series and the .str accessor will work. Commented Apr 17, 2020 at 19:05
  • Thank you. Doing a for loop can achieve the same thing as well. Commented Apr 17, 2020 at 19:11

1 Answer 1

2

What about df['date'].loc[2:4].str.replace('2016', 16')?

By selecting ['date'] first you know you are dealing with a series which does have a string attribute.

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution works, I guess df.loc[2:4,"date"].str.replace("2016","16") is the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.