Comparison with astype(int)

Tentatively convert your column to int and test with np.array_equal:

np.array_equal(df.v, df.v.astype(int))
True

float.is_integer

You can use this python function in conjunction with an apply:

df.v.apply(float.is_integer).all()
True

Or, using python's all in a generator comprehension, for space efficiency:

all(x.is_integer() for x in df.v)
True
Answer from coldspeed95 on Stack Overflow
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.api.types.is_float_dtype.html
pandas.api.types.is_float_dtype โ€” pandas 3.0.1 documentation
Whether or not the array or dtype is of a float dtype. ... Check whether the provided array or dtype is of a numeric dtype. ... Check whether the provided array or dtype is of an integer dtype. ... Check whether an array-like or dtype is of the object dtype. ... >>> from pandas.api.types import is_float_dtype >>> is_float_dtype(str) False >>> is_float_dtype(int) False >>> is_float_dtype(float) True >>> is_float_dtype(np.array(["a", "b"])) False >>> is_float_dtype(pd.Series([1, 2])) False >>> is_float_dtype(pd.Index([1, 2.0])) True
Discussions

python - Check if a column contains object containing float values in pandas data frame - Stack Overflow
Suppose I have a column that contains object which contains float(like this "12.45"). How can I check if this column exists in panda data frame. I want to find this column first and conve... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Find all columns of dataframe in Pandas whose type is float, or a particular type? - Stack Overflow
I have a dataframe, df, that has some columns of type float64, while the others are of object. Due to the mixed nature, I cannot use df.fillna('unknown') #getting error "ValueError: could not con... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to check for each column in a pandas dataframe whether it is a float or can be transformed into an integer - Stack Overflow
All other columns that contain "true" floats should stay as they are. What would be the quickest/easiest way to do this? ... One way to do this will be to divide the value in the column by 1. if the mod returns 0, then its an integer. If all the values of the mod is 0, then the column is an integer. With that, you can do the following to convert the column to integers. import pandas ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Function to check if object-dtype column value is float or string - Stack Overflow
I am trying to write a function which is equal to isnumber[column] function in excel dataset: feature1 feature2 feature3 123 1.07 1 231 2.08 3 122 ab 4 11... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Luasoftware
code.luasoftware.com โ€บ tutorials โ€บ pandas โ€บ pandas-check-column-is-float-and-convert
Pandas Check Column Is Float and Convert If Not
import pandas as pd items = [ {'name': 'Desmond', 'score': 1.5}, {'name': 'Jack', 'score': '0.369'}, {'name': 'Elon', 'score': 5}]df = pd.DataFrame(items) for index, row in df.iterrows(): print(row['name'], type(row['score'])) Desmond <class 'float'> Jack <class 'str'> Elon <class 'int'> if df.score.dtype != 'float64': df['score'] = df['score'].astype(float)for index, row in df.iterrows(): print(row['name'], type(row['score']))
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ find-all-columns-of-dataframe-in-pandas-whose-type-is-float-or-a-particular-type.aspx
Python - Find all columns of dataframe in Pandas whose type is float, or a particular type
# Importing pandas package import pandas as pd # Creating a dictionary d = { 'col1':[1.2,4.4,7.2], 'col2':[2,5,8], 'col3':[3.9,6.2,9.1], 'col4':['A','B','C'], 'col5':[True,False,True] } # Creating a dataframe df = pd.DataFrame(d) # Display Dataframe print("DataFrame :\n",df,"\n") # Filtering columns having dtype float result = df.select_dtypes(include=[float]) # Display result print("Result:\n",result)
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-check-if-the-pandas-index-is-a-floating-type
Python - Check if the Pandas Index is a floating type
October 13, 2021 - import pandas as pd # Creating Pandas index index = pd.Index([5.7, 6.8, 10.5, 20.4, 25.6, 30.8, 40.5, 50.2]) # Display the Pandas index print("Pandas Index...\n",index) # Return the number of elements in the Index print("\nNumber of elements in the index...\n",index.size) # Return the dtype of the data print("\nThe dtype object...\n",index.dtype) # check whether index values has only floats print("\nIndex values only consists of floats?\n",index.is_floating())
Top answer
1 of 2
1

One way to do this will be to divide the value in the column by 1. if the mod returns 0, then its an integer. If all the values of the mod is 0, then the column is an integer. With that, you can do the following to convert the column to integers.

Check if dataframe contains only float & ints

import pandas as pd
df = pd.DataFrame({'col1':[1,2,3,4,5,6],
                    'col2':[1.0,2.0,3.0,4.0,5.0,6.0],
                    'col3':[1.1,2.1,3.1,4.1,5.1,6.1]})

print (df.info())

for col in df.columns:
    if all(df[col]%1==0): df[col] = df[col].astype(int)

print (df.info())

Sample df is:

   col1  col2  col3
0     1   1.0   1.1
1     2   2.0   2.1
2     3   3.0   3.1
3     4   4.0   4.1
4     5   5.0   5.1
5     6   6.0   6.1

Info gives us:

Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   col1    6 non-null      int64  
 1   col2    6 non-null      float64
 2   col3    6 non-null      float64

After the check and conversion, the dtypes are:

 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   col1    6 non-null      int64  
 1   col2    6 non-null      int64  
 2   col3    6 non-null      float64

Check if dataframe contains varying dtypes

Since you want to test this only for floats and ints, you can add the condition before you check for mod of 1.

import pandas as pd
df = pd.DataFrame({'col1':[1,2,3,4,5,6],
                    'col2':[1.0,2.0,3.0,4.0,5.0,6.0],
                    'col3':[1.1,2.1,3.1,4.1,5.1,6.1],
                    'col4':['a','b','c','d','e','f'],
                    'col5':[True,True,True,False,False,False],
                    'col6':pd.date_range('2021.01.01', '2021.01.06').tolist()
                })

print (df)

print (df.info())

for col in df.columns:
    if df[col].dtype.kind in ('if') and all(df[col]%1==0): df[col] = df[col].astype(int)

print (df.info())

dtype.kind can be used to check i for int, f for float, b for bool, O for object and M for datetime. More details about numpy.dtype.kind available in the link here.

The output of this will be:

col1  col2  col3 col4   col5       col6
0     1   1.0   1.1    a   True 2021-01-01
1     2   2.0   2.1    b   True 2021-01-02
2     3   3.0   3.1    c   True 2021-01-03
3     4   4.0   4.1    d  False 2021-01-04
4     5   5.0   5.1    e  False 2021-01-05
5     6   6.0   6.1    f  False 2021-01-06
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 6 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   col1    6 non-null      int64         
 1   col2    6 non-null      float64       
 2   col3    6 non-null      float64       
 3   col4    6 non-null      object        
 4   col5    6 non-null      bool          
 5   col6    6 non-null      datetime64[ns]
dtypes: bool(1), datetime64ns, float64(2), int64(1), object(1)
memory usage: 374.0+ bytes
None
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 6 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   col1    6 non-null      int64         
 1   col2    6 non-null      int64         
 2   col3    6 non-null      float64       
 3   col4    6 non-null      object        
 4   col5    6 non-null      bool          
 5   col6    6 non-null      datetime64[ns]
dtypes: bool(1), datetime64ns, float64(1), int64(2), object(1)
memory usage: 374.0+ bytes
None
2 of 2
1

A quick way is to iterate through the dataframe, check if it is a float, compare to the integer version and finally concatenate:

 from pandas.api.types import is_float_dtype

columns = [col.astype(int) 
           if is_float_dtype(col) 
           and (col.eq(col.astype(int)).all()) 
           else col
           for _, col in df.items()]

pd.concat(columns, axis=1)


    no  col_1   col_2   col_3
0   1   1   0   5.4
1   2   0   1   1.0

There may be a better way though. So, let's wait for more answers from the community.

Dumping into numpy gives a bit more speed:

arr = df.to_numpy()
filters = df.columns[np.any(arr != arr.astype(int), axis=0)]
df.astype({col: int 
           for col in df 
           if col not in filters})
Find elsewhere
Top answer
1 of 5
1

Iteritems is returning a tuple, ((123, '1.07'), 1.07) and since you want to loop over each value try the below code. You just need to remove .iteritems() and it will work like a charm.

df['feature2']=[1.07,2.08,'ab',3.04,'cde']
for item in df.feature2:
    if isinstance(item,float):
       print('yes')
    else:
       print('no')

Here is your output:

yes
yes
no
yes
no
2 of 5
1

I think there are two things you need to consider here:

  1. Methods for Dict vs DataFrame
  2. Difference between dtype (array-scalar types) and type (built-in Python types) - Reference (https://numpy.org/devdocs/reference/arrays.dtypes.html)

Point 1:

.iteritems() / .items() are methods for dictionaries, whereas if you're dealing with dtypes (and judging by the data you've provided), you're likely to be going through a DataFrame, in which you don't need to use the .iteritems() method to loop through each value. Side note, .iteritems() has been phased out by Python and is replaced by .items() (See discussion: When should iteritems() be used instead of items()?)

Point 2:

When using numpy or Pandas, the data type of values imported into the DataFrames are called dtypes. These need to be differentiated from their direct comparisons in Pythons, which Python refers to as just type. You should use the table under "Pandas Data Types" heading for mapping of dtype to type (Ref: https://pbpython.com/pandas_dtypes.html)

Now, in response to your question, this bit of code should solve your issue:

import pandas as pd

columns = ['feature1', 'feature2', 'feature3']
data = [[123, 1.07, 1],
        [231, 2.08, 3],
        [122, 'ab', 4],
        [111, 3.04, 6],
        [555, 'cde', 8]]

df = pd.DataFrame(data, columns=columns)

for value in df.feature2:
    if isinstance(value,float):
        print('yes')
    else:
        print('no')
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.api.types.is_integer_dtype.html
pandas.api.types.is_integer_dtype โ€” pandas 3.0.1 documentation
>>> from pandas.api.types import is_integer_dtype >>> is_integer_dtype(str) False >>> is_integer_dtype(int) True >>> is_integer_dtype(float) False >>> is_integer_dtype(np.uint64) True >>> is_integer_dtype("int8") True >>> is_integer_dtype("Int8") True >>> is_integer_dtype(pd.Int8Dtype) True >>> is_integer_dtype(np.datetime64) False >>> is_integer_dtype(np.timedelta64) False >>> is_integer_dtype(np.array(["a", "b"])) False >>> is_integer_dtype(pd.Series([1, 2])) True >>> is_integer_dtype(np.array([], dtype=np.timedelta64)) False >>> is_integer_dtype(pd.Index([1, 2.0])) # float False
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ stable โ€บ reference โ€บ api โ€บ pandas.api.types.is_integer_dtype.html
pandas.api.types.is_integer_dtype โ€” pandas 2.3.3 documentation
The array or dtype to check. ... Whether or not the array or dtype is of an integer dtype and not an instance of timedelta64. ... >>> from pandas.api.types import is_integer_dtype >>> is_integer_dtype(str) False >>> is_integer_dtype(int) True >>> is_integer_dtype(float) False >>> is_integer_dtype(np.uint64) True >>> is_integer_dtype('int8') True >>> is_integer_dtype('Int8') True >>> is_integer_dtype(pd.Int8Dtype) True >>> is_integer_dtype(np.datetime64) False >>> is_integer_dtype(np.timedelta64) False >>> is_integer_dtype(np.array(['a', 'b'])) False >>> is_integer_dtype(pd.Series([1, 2])) True >>> is_integer_dtype(np.array([], dtype=np.timedelta64)) False >>> is_integer_dtype(pd.Index([1, 2.])) # float False
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ python-check-if-value-is-float-in-pandas
How to Check if a Value is Float in Pandas: Complete Guide 2026 - Python check if value is float in pandas
December 20, 2025 - This guide covers all methods available ... type handling. The most robust way to check if a pandas Series or column contains float data is using pd.api.types.is_float_dtype()....
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ figure out which column of a dataframe is int vs float etc and how to convert to float?
r/learnpython on Reddit: Figure out which column of a dataframe is int vs float etc and how to convert to float?
April 26, 2023 -

I'm working on a classifier based on a log regression model. There's a lot to it but I don't really know know how to use python (this is a class project, and I haven't had any prior Python experience). I'm trying to normalize my data and am using example code from keras.

My normalization is failing due to an error that reads this:

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int).

So my questions are- how can I see which columns in my dataframe are datatype int?

How can I convert an into to a float? (I assume this will fix my problem)

I've tried to print using my_dataframe.dtype but that hasn't worked.

Thanks in advance for the help, and sorry for the basic question. Python syntax and stuff has me totally lost. I'm having a really hard time understanding the python/tf/keras/numpy doc and I am running out of time + can essentially only work this project in my free time.

๐ŸŒ
Data Science Parichay
datascienceparichay.com โ€บ home โ€บ blog โ€บ pandas โ€“ check if column datatype is numeric
Pandas - Check if column datatype is numeric - Data Science Parichay
November 11, 2022 - In this method, we use the .dtype.kind attribute to check if the column datatype is in biufc where biufc : b bool, i int (signed), u unsigned int, f float, c complex. ... Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers. Now, Let us look at examples of Each method discussed above to check if specific column elements are of Numeric datatype or not. Note: In case, you donโ€™t have a pandas Dataframe, use the below simple method to create one.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Index.is_floating.html
pandas.Index.is_floating โ€” pandas 2.3.3 documentation
Check if the Index is a floating type. Deprecated since version 2.0.0: Use pandas.api.types.is_float_dtype instead
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.api.types.is_numeric_dtype.html
pandas.api.types.is_numeric_dtype โ€” pandas 3.0.1 documentation
Check whether the provided array or dtype is of a signed integer dtype. ... >>> from pandas.api.types import is_numeric_dtype >>> is_numeric_dtype(str) False >>> is_numeric_dtype(int) True >>> is_numeric_dtype(float) True >>> is_numeric_dtype(np.uint64) True >>> is_numeric_dtype(np.datetime64) False >>> is_numeric_dtype(np.timedelta64) False >>> is_numeric_dtype(np.array(["a", "b"])) False >>> is_numeric_dtype(pd.Series([1, 2])) True >>> is_numeric_dtype(pd.Index([1, 2.0])) True >>> is_numeric_dtype(np.array([], dtype=np.timedelta64)) False