LIU ZHIWEN
LIU ZHIWEN

Reputation: 173

What the difference between df[:,'column_name'] and df['column_name'] when querying data from a pandas.dataframe

What the difference between df[:,'column_name'] and df['column_name'] when querying data from pandas's DataFrame.

When I use df[:,'Energy_supply'] I come into this

TypeError: unhashable type: 'slice'.

But when I use df['column_name'] I get what I want.

My data is a 228 rows × 3 columns dataframe with a country_name index and the three columns' name are ['Energy Supply', 'Energy Supply per Capita', '% Renewable'].enter image description here

Upvotes: 0

Views: 6166

Answers (2)

Wariored
Wariored

Reputation: 1343

df['index'] 

is for accessing to the column 'index' not for specific data.

Note that in python (Numpy), you can access the data by df[:, 2] [line, column]

In Pandas use, instead :

df.loc[:, 'index'] # [line number, column 'index'], : means all

Upvotes: 1

Nikhil Verma
Nikhil Verma

Reputation: 1730

df[:,'index']

is for accessing elements from an array (slice operation), index is the column index (0 to n-1)

Equivalent operation for pandas is

df.loc[:,int_index]


df['column_name'] is for accessing columns from a pandas data frame.

Have a look at this:

https://www.shanelynn.ie/select-pandas-dataframe-rows-and-columns-using-iloc-loc-and-ix/

Upvotes: 0

Related Questions