0

I want to slice metope columns that are located several columns away from each other. I'm trying to write code that easy without having to write the code repeatedly:

df (See below for example) where columns are from A to H, with many rows containing some data (x).

How do I slice multiple randomly spaced columns, the say A, D, E, G, all in minimum amount of code. I don't want to rewrite loc code (df.loc['A'], df.loc['C:E'], df.loc['G'])?

Can I generate a list and loop through it or is there a shorter/quicker way?

Ultimately my goal would be to drop the selected columns from the main DataFrame.

    A B C D E F G H
0   x x x x x x x x

1   x x x x x x x x

2   x x x x x x x x

3   x x x x x x x x

4   x x x x x x x x
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
moman
  • 1
  • 3

1 Answers1

0

You might harness .iloc method to get columns by their position rather than name, for example:

import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6],'C':[7,8,9],'D':[10,11,12],'E':[13,14,15]})
df2 = df.iloc[:, [0,2,4]]
print(df2)

output:

   A  C   E
0  1  7  13
1  2  8  14
2  3  9  15

If you need just x random columns from your df which has y columns, you might use random.sample for example if you want 3 column out of 5:

import random
cols = sorted(random.sample(range(0,5),k=3))

gives cols which is sorted list of three numbers (thanks to sorted order of columns will be preserved)

Daweo
  • 31,313
  • 3
  • 12
  • 25
  • Okay - thanks. What if i want to drop rows from the selected columns based on a criteria e.g. for Column A if row value > a, and Column D if value < d? – moman Feb 03 '21 at 10:01