Home > OS >  What is the difference of int and 'int' in python?
What is the difference of int and 'int' in python?

Time:12-01

I'm doing my homework in python and I happen to meet a very tricky problem: the difference between int and 'int' in python? Here is the code:

type(1) == 'int'
type(1) == int

and here is the result:

False
True

I firstly thought that maybe 'int' here is purely a string, but later I used pd.DataFrame for another test:

train_data.deposit # train_data is a pd.DataFrame and deposit is a column with dtype int
train_data.deposit.dtype == 'int'
train_data.deposit.dtype == int

and got the result:

True
True

So is there a difference between int and 'int' in python, if so, what is it? Thank you so much for your kind answer.

CodePudding user response:

anything in quotes is a string.

type() in python returns the type of an object. So type(1) is the type int (integer) and the type int is equal to int. But the type int is not equal to 'int' the string.

Onto the example with pandas:

pandas dtype does not return a python class. It returns an object, which can be checked to be a type. So the == operator in python can be defined for all objects (Method eq). And dtype can be compared with python buildin types and strings.

Example

import pandas as pd
df = pd.DataFrame([i for i in range(10)],columns=["test"]).astype(int)
# df is now a pandas DataFrame with type dtype(int32) therefore:
type(df.test.dtype) # -> <class 'numpy.dtype[int32]'>
df.test.dtype == 'int' # True
df.test.dtype == int # True

Further Information

To overwrite the equals method you have to define a eq(this, other) Method inside a class. Feel free to google or follow tutorials like this one

CodePudding user response:

Here is the difference :- int is used to do things like determine the type of a variable (as you've done in your example). int() is used to convert a non-int variable to an int (i.e. "45" becomes 45).

  • Related