In pandas, the DataFrame.keys()
method is used to get the axis info for pandas instance. Pandas instance or object can be either Series or a DataFrame.
Note: Axis info contains column names and data type.
DataFrame.keys()
It does not take any argument value.
This method returns a Python iterator object.
In this example, we discuss keys()
with DataFrame:
# importing pandas as pd aliasimport pandas as pd# initializing a nested listdata = [['China', 15], ['America', 21], ['Pakistan', 0.4]]# Creating the DataFramedf = pd.DataFrame(data, columns = ['Country', 'GDP'])# Print the DataFrameprint(df.keys())
In the code snippet above, we create a DataFrame with column names Country
and GDP
. Next, we invoke the keys()
function to get the info axis.
DataFrame
by using Country
and GDP
as column names. keys()
to extract info axis.In this example, we discuss keys()
with Series:
# importing pandas as pdimport pandas as pdimport numpy as np# creating a numpy arraydata = np.array(['e','d','u','c','a','t','i','v','e'])# creating a series_series = pd.Series(data)# to find the indexprint(_series.keys())
In the code snippet above, we create a series of the character array and invoking keys()
to get axis info.
Series()
to convert above create character array into a Series object.keys()
to extract info axis.