Why does using df[[column_name]] dislays a DataFrame?
It may happend because when you give single column_name as a string it takes it perform selection and return single value based on the search key column_name.
But when you provide same column_name contained in a list it tries to fetch all the keys of the list which in one in this case. Hence resulting a dataframe.
I guess they are using some standard logic to return dataframe if list is provided irrespective of length of list.
import pandas as pd
df = pd.DataFrame(columns=["a","b","c"],
data=[[1,4,7],[2,5,8],[3,6,9]])
column_name = "a"
print(type(df[column_name]))
print(type(df[[column_name]]))
output:
<class 'pandas.core.series.Series'>
<class 'pandas.core.frame.DataFrame'>
I was just asking myself: I understand that calling df[column_name] displays a Series because a DataFrame is built of different arrays.
Though, why does calling df[[column_name]] (column_name being only one column) returns a DataFrame and not a Series ? I'm ont sure to understand the logic behing how Pandas was built here
Thanks :)
I was trying to explain to my students why calling a list of one element displays a dataframe and not a Series, but did not manage