1

I have an original array in python : t_array

t_array=(['META' , 'AAPL' , 'AMZN' , 'NFLX' , 'GOOG' ])

sample = random.sample (t_array, 3)

print=( 'sample')

and got this :

['AAPL', 'AMZN', 'META']

Now when I run the (1) code again the sample refreshes to a new triple element array like the following :

['AMZN', 'META', 'NFLX'] or so

I wish to get all possible combinations without replacement from the original array t_array and print them at once in a dataframe format or series format so I can refer to them by index in my further code

How do I code that in python?

machine: currently using jupyter notebook on mac osx

ScottC
  • 3,941
  • 1
  • 6
  • 20
  • Welcome to SO! +1 for sharing the code, however, for easier reading, I would suggest pulling in all the relevant code in one code block and update your question. – medium-dimensional Dec 23 '22 at 05:44
  • Does this answer your question? [Get unique combinations of elements from a python list](https://stackoverflow.com/questions/18201690/get-unique-combinations-of-elements-from-a-python-list) – medium-dimensional Dec 23 '22 at 05:49
  • Also, you are using a [built-in keyword](https://docs.python.org/3/library/functions.html) as a variable i.e. `print = ('sample')`. This would create a problem later in the code when you want to actually print something (e.g. try `print(sample)` after `print = ('sample')`). I hope this was a typo and not intended. – medium-dimensional Dec 23 '22 at 05:56

1 Answers1

1

You can use the combinations function from itertools.

df = pd.DataFrame(combinations(t_array, 3))

Code:

from itertools import combinations
import pandas as pd

t_array=(['META' , 'AAPL' , 'AMZN' , 'NFLX' , 'GOOG' ])

df = pd.DataFrame(combinations(t_array, 3))

print(df)

Output:

      0     1     2
0  META  AAPL  AMZN
1  META  AAPL  NFLX
2  META  AAPL  GOOG
3  META  AMZN  NFLX
4  META  AMZN  GOOG
5  META  NFLX  GOOG
6  AAPL  AMZN  NFLX
7  AAPL  AMZN  GOOG
8  AAPL  NFLX  GOOG
9  AMZN  NFLX  GOOG
ScottC
  • 3,941
  • 1
  • 6
  • 20