Reputation: 3
I have 19 columns (q1 to q19) in a DataFrame 'users' I want to convert from float to int. Instead of manually typing it out is there a way to automate the process?
Code I have so far is:
users.q1 = users.q1.astype(int)
Upvotes: 0
Views: 210
Reputation: 1594
you can try this
df.loc[:, 'q1':'q19'] = df.loc[:, 'q1':'q19'].astype(int)
Upvotes: 0
Reputation: 2190
Pass a list of the columns that you want to alter:
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [2, 3, 8], 'C':[5, 9, 12]})
df1[['A', 'B']] = df1[['A', 'B']].astype('float')
print(df1)
Output:
A B C
0 1.0 2.0 5
1 2.0 3.0 9
2 3.0 8.0 12
Instead of altering line for line, we can simplify to one line for all of the columns that need to be changed.
Upvotes: 1
Reputation: 71570
Try this:
for i in users.columns:
if <condition>:
users[i] = users[i].astype(int)
Upvotes: 0