I have an Excel sheet with 3 rows and 5 columns that I want to get all possible combinations of into one row for every combination. Using itertools
gets all the combinations, but joining them into one row for each result and with different variables is too hard for me.
Type Sort Length Width Weight
Small P1 4 1.3 11
Medium P2 2 1.6 4
Large P3 7 1.1 8
Expected results (all possible combinations of all lengths combined into one row for each iteration):
Small, P1 4 1.3 11
Small, Medium P1,P2 6 2.9 15
Small, Medium,Large P1,P2,P3 13 4.0 23
Medium P2 2 1.6 4
Medium, Large P2,P3 9 2.7 12
Large P3 7 1.1 8
Edit:
import pandas as pd
import itertools
read_file = pd.read_excel (r'Data_list.xlsx')
read_file.to_csv ('Data_list.csv', index=True, header=True)
input_dict = read_file.to_dict('data_list')
output_dict = dict()
k = 0
for dict_size in range(1,len(input_dict)+1):
for combination in itertools.combinations(input_dict, dict_size):
d=len(combination)
k = k+1
res[k] = input_dict[i]
if d == 1:
res[k] = {key: res[i][key] + input_dict[i].get(key, '') for key in res[i].keys()}
else:
res[k] = {key: res[i][key] + input_dict[1].get(key, '') for key in res[i].keys()}
df = pd.DataFrame(res)
df = df.T
print(df)
df.to_excel('Combined_data.xlsx')
The answer is in your question :)
Let's assume that you transform your excel into a CSV, which you read as a list of dicts (you can learn how to do this by reading the Python documentation)
You will need to use itertools.combination on i
rounds (to have i-elements combinations), i
going from 1 to the length of the initial list (included)
For each resulting list of combinations, you will have to perform your own transformation of elements (sum, string concatenation...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.