1

I have a table:

simple_table

And I would like to slice the first three columns, how can I do this?

I've looked at this other post: Finding top N columns for each row in data frame, but that is overkill for me.

I've tried:

df1 = df.iloc[:,0:3]

But this gives the error: IndexingError: Too many indexers

EDIT:

More detailed code with the added ix

    cols = [col for col in df.columns if col != 'stream']
    candidates = df.loc[url,cols]

    dfSorted = candidates.sort_values(ascending=False)

    big_three = dfSorted.ix[:,0:3]
Community
  • 1
  • 1
Stanko
  • 4,275
  • 3
  • 23
  • 51
  • 1
    What is your pandas version? I guess slicing columns with .iloc was introduced later. It works fine on v18.0. .ix may work on earlier versions if I remember correctly. – ayhan May 02 '16 at 12:01
  • @ayhan I have version 0.17.1 – Stanko May 02 '16 at 12:02
  • 1
    @Stanko - what is `print df.index` and `print df.columns` ? – jezrael May 02 '16 at 12:09
  • @jezrael When doing df.columns I get: 'Series' object has no attribute 'columns'. So `.loc` returns a Series object? – Stanko May 02 '16 at 12:15
  • 3
    Yes, problem is `dfSorted` is `Serie`, not `DataFrame`, so you cannot index columns in `Serie`, because no columns. – jezrael May 02 '16 at 12:16

1 Answers1

3

I think you can use apply with nlargest for selecting top 3 columns and values of DataFrame candidates:

import pandas as pd

df = pd.DataFrame({'A': {'a': 1, 'c': 5, 'b': 2, 'd': 3}, 
                   'C': {'a': 8, 'c': 7, 'b': 8, 'd': 7}, 
                   'B': {'a': 4, 'c': 1, 'b': 5, 'd': 4}, 
                   'D': {'a': 5, 'c': 3, 'b': 9, 'd': 1}, 
                   'stream': {'a': 1, 'c': 2, 'b': 2, 'd': 3}})
print df
   A  B  C  D  stream
a  1  4  8  5       1
b  2  5  8  9       2
c  5  1  7  3       2
d  3  4  7  1       3


cols = [col for col in df.columns if col != 'stream']
candidates = df.ix['a':'c', cols]

print candidates
   A  B  C  D
a  1  4  8  5
b  2  5  8  9
c  5  1  7  3

print candidates.apply(lambda x: zip(x.nlargest(3).index, x.nlargest(3).values), axis=1)
a    [(C, 8), (D, 5), (B, 4)]
b    [(D, 9), (C, 8), (B, 5)]
c    [(C, 7), (A, 5), (D, 3)]
dtype: object

What is same as:

def f(x):
    #print x.nlargest(3)
    #print zip(x.nlargest(3).index, x.nlargest(3).values)
    return zip(x.nlargest(3).index, x.nlargest(3).values)

print candidates.apply(f, axis=1)
a    [(C, 8), (D, 5), (B, 4)]
b    [(D, 9), (C, 8), (B, 5)]
c    [(C, 7), (A, 5), (D, 3)]
dtype: object
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252