[英]pandas dataframe : save & read excel sheet | handling integers as strings
[英]Get and then join all combinations of rows with strings and integers in Excel sheet
我有一個包含 3 行和 5 列的 Excel 工作表,我希望將所有可能的組合都放在一行中。 使用itertools
可以獲得所有組合,但是對於每個結果和不同的變量將它們加入一行對我來說太難了。
Type Sort Length Width Weight
Small P1 4 1.3 11
Medium P2 2 1.6 4
Large P3 7 1.1 8
預期結果(每次迭代將所有長度的所有可能組合組合成一行):
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
編輯:
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')
答案就在你的問題中:)
假設您將 excel 轉換為 CSV,您可以將其讀取為 dicts 列表(您可以通過閱讀 Python 文檔了解如何執行此操作)
您將需要在i
輪上使用itertools.combination (以獲得 i 元素組合), i
從 1 到初始列表的長度(包括)
對於每個結果組合列表,您必須執行自己的元素轉換(總和,字符串連接......)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.