Hello, everyone I'm running Python on Jupiter laptop
I'm asking because I'm not sure how to write a for statement for a variable.
The variables are from Year1 to Year10.
# Year1 type conversion
index = 1
while(index<=57):
colname = Year1.columns[index]
col = getattr(Year1, colname)
Year1[colname] = col.astype(float)
index+=1
col = getattr(Year1, 'Y')
Year1['Y'] = col.astype(int)
# Year 2 type conversion
index = 1
while(index<=57):
colname = Year2.columns[index]
col = getattr(Year2, colname)
Year2[colname] = col.astype(float)
index+=1
col = getattr(Year2, 'Y')
Year2['Y'] = col.astype(int)
How do I write a for statement that only changes the number after the year?
I'd really appreciate it if you could help me!
python pandas dataframe casting
for YearN in [Year1, Year2, Year3, Year4]:
# Repeated code
You can put the variables that you change in the list, take them out one by one, and write the repetitive code in the loop.
Looking at the code, it seems that the numerical values are read in text and are trying to convert them into numerical values. I'm making it too complicated.
You can also asttype(float)
for the entire data frame. Or it looks better to write to_numerical
.
© 2024 OneMinuteCode. All rights reserved.