convert entire pandas dataframe to integers in pandas (0.17.0)

后端 未结 3 929
长发绾君心
长发绾君心 2020-11-30 05:21

My question is very similar to this one, but I need to convert my entire dataframe instead of just a series. The to_numeric function only works on one series at

3条回答
  •  情书的邮戳
    2020-11-30 06:11

    apply() the pd.to_numeric with errors='ignore' and assign it back to the DataFrame:

    df = pd.DataFrame({'ints': ['3', '5'], 'Words': ['Kobe', 'Bryant']})
    print ("Orig: \n",df.dtypes)
    
    df.apply(pd.to_numeric, errors='ignore')
    print ("\nto_numeric: \n",df.dtypes)
    
    df = df.apply(pd.to_numeric, errors='ignore')
    print ("\nto_numeric with assign: \n",df.dtypes)
    

    Output:

    Orig: 
     ints     object
    Words    object
    dtype: object
    
    to_numeric: 
     ints     object
    Words    object
    dtype: object
    
    to_numeric with assign: 
     ints      int64
    Words    object
    dtype: object
    

提交回复
热议问题