0

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)
1
  • Sorry I forgot to mention there are other columns in the dataframe I want to keep as other datatypes Commented Jun 12, 2018 at 4:08

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

One thing, float in the astype does not need to be a string
@U8-Forward I am fairly certain that in numpy it does have to be a string, which is why I do so in Pandas. That may not be accurate, but I vaguely remember it having to be a string a few years ago, and I assumed it was the same in pandas. I could be wrong.
Ok but at least i know now that you can just do .astype(float)
@U8-Forward Thanks. I will test if you can do that in numpy. I recall getting a syntax error in Numpy when I attempted to pass float in the "dtype" argument a few years ago. So I have figured it was the same in Pandas ever since. Thanks for the knowledge. I just thought that you had to pass a string.
0

you can try this

df.loc[:, 'q1':'q19'] = df.loc[:, 'q1':'q19'].astype(int)

Comments

0

Try this:

for i in users.columns:
    if <condition>:
        users[i] = users[i].astype(int)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.