Megan Martin
Megan Martin

Reputation: 221

How to convert float to int and concatenate with a string?

I have an array of years ,por. The years are currently floats and include a decimal like 1942.0. I want to remove the decimal place and add "-12-31" so that I have an array with entries that look like "1942-12-31". I wrote the loop below but when I run it, the decimal remains and the first few instances of the array remain unchanged. Where am I going wrong?

por=CMStations.por
for i in por:
    int(i)
    por.loc[i]=str(i)+"-12-31"

Upvotes: 0

Views: 634

Answers (4)

loopassembly
loopassembly

Reputation: 3873

You can go on with this :

por=[2021.0,2022.0,2023.0,2024.0,2025.0]
por_new=[]
for item in por:
    if item!=int:
        por_new.append(str(int(item))+"-12-31")
print(por_new)

OUTPUT

['2021-12-31', '2022-12-31', '2023-12-31', '2024-12-31', '2025-12-31']

Upvotes: 0

Pedro
Pedro

Reputation: 330

It depends on the type of variable por is. If it is an array of floats than you can only change it to another float not a string. For that matter, create a list for the new values (strings) like this:

import numpy as np
por = np.array([1942.0,1943.1,1944.2])
por_string = []
for i in por:
    por_string.append(str(int(i))+"-12-31")

The output is:

['1942-12-31', '1943-12-31', '1944-12-31']

Upvotes: 0

Jose
Jose

Reputation: 1

Assume por is a list in Python(I don't think array is more common in Python but they are similar), the following code works. You need to assign int(i) to a new value, like i itself to replace it with int. Otherwise, there's no change made to i effectively. Also, you can't directly change a list, so I created a new list and assign it back to the old list.

    new_por = list()
    for i in por:
        i = int(i)
        i = str(i) + "-12-31"
        new_por.append(i)
    por = new_por

Upvotes: 0

havingaball
havingaball

Reputation: 378

The decimal remains because you aren't assigning int(i) to anything. Try

por=CMStations.por
for i in por:
    por.loc[i]=str(int(i))+"-12-31"

Upvotes: 2

Related Questions