How to view the data type of a column or specific value in a Pandas DataFrame
Published on Aug. 22, 2023, 12:16 p.m.
To view the data type of a column or specific value in a Pandas DataFrame, you can use the dtypes
attribute to view the data types of all columns:
import pandas as pd
# create a Pandas DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['4', '5', '6']})
# view the data types of all columns
print(df.dtypes)
This will output the data types of all columns in the DataFrame.
If you want to view the data type of a specific value, you can use the dtype
attribute of the Series object that represents the column containing the value:
import pandas as pd
# create a Pandas DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['4', '5', '6']})
# view the data type of a specific value
print(df['A'][0].dtype)
In this example, we view the data type of the first value in the column ‘A’ of the DataFrame.
Alternatively, you can use the info()
method to view the data types of all columns, and the number of non-null values in each column:
import pandas as pd
# create a Pandas DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['4', '5', '6']})
# view the data types of all columns and number of non-null values
print(df.info())
This will output the data types and number of non-null values for each column in the DataFrame.