what’s the difference between df[‘’] and df[[‘’]]

Viewed 515

I have written a function to show elbow to select the optimal value of K of Kmeans.

from sklearn.cluster import KMeans
def show_elbow(df):
    distance_list=[]
    K = range(1,9)
    for k in K:
        kmeams=KMeans(n_cluster=k,max_iter=100)
        kmeans=KMeans.fit(df)
        distance_list.append(kmeans.inertia_)
    plt.plot(K,distance_list,'bx-')

When I use this function, df[''] causes error while df[['']] doesn’t. I don’t know the reason.

3 Answers

Difference:

  • df['a'] gives a Series object, which is one column, example:

    >>> df['a']
    0    1
    1    2
    2    3
    Name: a, dtype: int64
    >>> 
    
  • df[['a']] selects multiple columns, but in this case only one column is inside the list, therefore the DataFrame type is retained:

    >>> df[['a']]
       a
    0  1
    1  2
    2  3
    >>> 
    

When you write df["] you are basically accessing a set of number values, but when you use df[["]] you are getting a DataFrame object which is compatible with your code.

Returns different type :

type(df['a'])
Out[1]: pandas.core.series.Series

type(df[['a']])
Out[2]: pandas.core.frame.DataFrame
Related