Reputation: 3299
I have several data frames which I need to convert the datatypes to integers. I tried using a for loop to try and make my code a bit tidier, but after running this and checking the dtypes they don't change. Anyone know why this could be/any work arounds? I think its something to do with creating copies. An example of similar code below:
for df in [df1, df2, df3]:
df = df.astype(int)
Upvotes: 0
Views: 1278
Reputation: 3299
I've found a nicer why to code this using a function. It's not quite as elegant as I initially hoped with a for loop, but will save me writing out long lists of column names to be changed several times:
def to_int(df, cols):
df[cols] = df[cols].astype(int)
return df
df = to_int(df, ['col1', 'col2'])
Allows me to change only the data type of the desired columns.
Upvotes: 0
Reputation: 433
The problem here is that you are not changing your initial objects, only your variable df.
To change your initial dataframes you could do the following :
df_list = [df1, df2, df3]
for i in range(len(df_list)):
df_list[i] = df_list[i].astype(int)
Upvotes: 1