-2

I have dataframe with given names of columns and I want to to return a column with specified name:

name_of_column = 'name1'  # string variable

I tried to use this:

dataframe.iloc[:, name_of_column]

But it did not work. What should I do?

jpp
  • 159,742
  • 34
  • 281
  • 339
  • https://stackoverflow.com/help/how-to-ask – najeem Jan 20 '19 at 10:57
  • welcome as a new programmer. your question already have answers to how to do in the documentation. http://pandas.pydata.org/pandas-docs/stable/indexing.html you might not find it immediately, but it's there – ahed87 Jan 20 '19 at 11:01
  • Possible duplicate of [How to take column-slices of dataframe in pandas](https://stackoverflow.com/questions/10665889/how-to-take-column-slices-of-dataframe-in-pandas) – Amit Gupta May 02 '19 at 05:34

2 Answers2

0

You can just do:

dataframe[column_name]

Will select the column.

iloc() method finds an item in pandas by index.

More examples the selecting data you can find in Pandas Indexing and Selecting Data

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
tiagohbalves
  • 174
  • 1
  • 8
0

Use loc instead of iloc and your syntax will work. iloc is for indexing by integer position (this is what the i stands for), while loc is for indexing by label. So you can use:

dataframe.loc[:, name_of_column]

Having said this, the more usual way to retrieve a series is to use __getitem__ directly:

dataframe[name_of_column]
jpp
  • 159,742
  • 34
  • 281
  • 339