Home > Software engineering >  Get DataFrame columns by index
Get DataFrame columns by index

Time:08-27

I have the following code:

values = ta.service(data["T"], data["H"])

print(values)

The variable values is a DataFrame and is printed as:

|            |     OT     |     OH     |
|------------|------------|------------|
| Timestamp  |            |            |
| 26-06-2020 | 19.54      |  NaN       |
| 03-07-2020 | 16.024     |  17.20     |
| 10-07-2020 | 19.26      |  25.89     |
----------------------------------------

I tried to get only the OT and OH columns in different ways, for example:

print(values.iloc[:, 1:2])

But, for this, I got:

|            |     OH     |
|------------|------------|
| Timestamp  |            |
| 26-06-2020 |  NaN       |
| 03-07-2020 |  17.20     |
| 10-07-2020 |  25.89     |
---------------------------

Shouldn't I get the columns 1 and 2, e.g., OT and OH? I also tried:

print(values.columns[1:2]) 

But I got:

Index(['OH'], dtype='object')

What am I missing?

CodePudding user response:

try this:

values[["OT","OH"]]

CodePudding user response:

As mentioned by Quang Hoang, iloc works like slicing. So you could do:

values.iloc[:,0:2]

or with labels

values.loc[:,["OH", "OT"]]
  • Related