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
CodePudding user response:
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