How to store the result of an iteration in a new variable using python?

Asked

Viewed 917 times

1

Good morning, everyone!

I’m analyzing a conjunto de dados de compartilhamento de bicicletas. In that dataset there is a column called 'birthyear', indicating the year of birth of the user.

I am trying to turn this column into a time series column. To do this, I have created the following iteration:

saved this column in a variable called yr

for i in yr:
    x = datetime(yr[i],1,1)
    print(x)'

The exit is:

1964-01-01 00:00:00
1986-01-01 00:00:00
1967-01-01 00:00:00
1976-01-01 00:00:00
1991-01-01 00:00:00
1975-01-01 00:00:00
1975-01-01 00:00:00

But when I store the output in the variable 'x', it does not store this list, but only the first line.

Saída: datetime.datetime(1975, 1, 1, 0, 0)

How can I solve this problem ?

  • would be able to post the yr code here?

  • yr = dataframe.birthyear

1 answer

4


If I understand correctly, you can add elements in a python list using append

x=[]
for i in yr:
    x.append(datetime(yr[i],1,1))

print(x)

This will add all loop iterations to the list x, the way you demonstrated in your code, with each iteration the variable x is overwritten, at the end of the loop the variable x will only have stored the value of the last iteration.

  • Thank you very much !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.