3

the below python code works with a pandas dataframe but I was wondering how to make it more efficient.

columns = list(data)
lenn=len(columns)
lenn

i=0
while i<lenn:
    j=i+1
    while j <lenn:
        print(data.iloc[:,i]*data.iloc[:,j])
        #print(data.iloc[:,j])
        j=j+1
    i=i+1
andrewcz
  • 53
  • 5

1 Answers1

1

We can do shift

data.shift(axis=1)*data

Update 1

s=data.shift(axis=1)*data
for x in list(s):
    print(s.loc[:,s])

Update 2

for x in list(data):
    print(data.loc[:,x],data.shift(axis=1).loc[:,x])

Update 3

import itertools
t=list(itertools.combinations(range(df.shape[1]), 2))
for x in t:
    print(data.iloc[:,x[0]],data.iloc[:,x[1]])
BENY
  • 317,841
  • 20
  • 164
  • 234
  • amazing! but what if I wanted to select each column? – andrewcz Oct 13 '19 at 00:08
  • @andrewcz change the shift to shift(1), check the update – BENY Oct 13 '19 at 00:12
  • does that select each column individually? what is i wanted to print out each column? – andrewcz Oct 13 '19 at 00:16
  • @andrewcz will update, also if the update work for you , would you like accept, check mark at the left – BENY Oct 13 '19 at 00:18
  • Amazing! thank you so much for your help!! what if just wanted to print out the columns not multiply them. just select every adjacent column? – andrewcz Oct 13 '19 at 00:24
  • If I wanted to print columns 1,2 and 1,3 and 1,4 and then 2,3 2,4 and 3,4.... – andrewcz Oct 13 '19 at 00:33
  • Thats amazing!! yes!! Thank you!! although i dont really understand the code. Is there a simpler way possibly. – andrewcz Oct 13 '19 at 00:39
  • @andrewcz check what i did by using intertools in here https://stackoverflow.com/questions/36429507/python-combinations-without-repetitions – BENY Oct 13 '19 at 00:41