0

I have dataframe that looks like this:

State   State_theft_sum Model_1 Model_year_1
Alabama 2154    Chevrolet Pickup (Full Size)    2005.0  
Alaska  547 Chevrolet Pickup (Full Size)    2003.0
Arizona 5270    Honda Accord    1997.0  

DF goes on and on, so changing values separately isn't the way. I though i might be able to replace them using result of loop which would format string as I want it to be, here is the loop:

for model_year in df_total['Model_year_1']:
    model_year = model_year.split('.')
    model_year = model_year[0]
    print(model_year)

Result of the loop:

2005
2003
1997
2004
1996
1997
(...)

I need this to be formatted as a string as I will use it as text for Choropleth chart.

Is there any way I can change the values inside a column of DF without needing to create new DF from the loop and then joining them and after that deleting the column with .0?

1 Answer 1

1

You could probably just convert it to a float, then to an int and then to a str to avoid the loop.

df["Model_year_1"] = df["Model_year_1"].astype('float').astype('int').astype('str')
Sign up to request clarification or add additional context in comments.

2 Comments

I tried doing that but then i have this error: "ValueError: invalid literal for int() with base 10: '2005.0'"
I didn't realize the years were strings. I've updated the answer.

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.