0

How do you get the last (or "nth") column in a dataFrame?

I tried several different articles such as 1 and 2.

df = pd.read_csv(csv_file)

col=df.iloc[:,0] #returns Index([], dtype='object')
col2=df.iloc[:,-1] #returns the whole dataframe
col3=df.columns[df.columns.str.startswith('c')] #returns Index([], dtype='object')

The commented out parts after the code is what I am getting after a print. Most of the time I am getting things like "returns Index([], dtype='object')"

Here is what df prints:

     date     open     high      low    close
0     0   2019-07-09 09:20:10  296.235  296.245  296...         
1     1   2019-07-09 09:20:15  296.245  296.245  296...         
2     2   2019-07-09 09:20:20  296.235  296.245  296...         
3     3   2019-07-09 09:20:25  296.235  296.275  296... 
Valentino
  • 7,291
  • 6
  • 18
  • 34
chess master1
  • 55
  • 1
  • 9

1 Answers1

0

df.iloc is able to refer to both rows and columns. If you only input one integer, it will automatically refer to a row. You can mix the indexer types for the index and columns. Use : to select the entire axis.

df.iloc[:,-1:] will print out all of the final column.

mcbridecaleb
  • 101
  • 1
  • 8
  • This is what the user already did and it did not return the expected result, as shown in the given code and the linked answers. `df.iloc[:,-1:]` is equivalent to `df.iloc[:,-1]` – G. Anderson Jul 09 '19 at 20:51