2

Anyone know how to convert all column values in dataframe to int?

lets say i have a dataframe containing

  A B C 

  1 2 1

  3 2 1

  1 4 5

dtypes is object how do i convert it to int or numeric

toti08
  • 2,448
  • 5
  • 24
  • 36
Ryan
  • 143
  • 1
  • 2
  • 10
  • 1
    You can use pandas module pd.to_numeric(df) for converting object into numeric values.['https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html'](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html) – Akash Badam Sep 24 '18 at 08:56
  • 3
    `df = df.astype(int)` – jezrael Sep 24 '18 at 08:57

1 Answers1

3

You can use pandas astype() function, pandas to_numeric may also give you the behaviour you want

a = pd.DataFrame({"A":["1",2,3], "B":[2,"2",4], "C":[1.0,1.0,5.0]})
a.dtypes

Out[8]: 
A     object
B     object
C    float64
dtype: object

b = a.astype(int)
b.dtypes
Out[10]: 
A    int32
B    int32
C    int32
dtype: object

b
Out[11]: 
   A  B  C
0  1  2  1
1  2  2  1
2  3  4  5
Sven Harris
  • 2,884
  • 1
  • 10
  • 20