Python 合并dataframe中的值以写入excel
我有一个看起来像Python 合并dataframe中的值以写入excel,python,excel,pandas,dataframe,Python,Excel,Pandas,Dataframe,我有一个看起来像 column1 column2 column3 colum4 column5 1 r_n_1 r_s_1 r_n_2 r_s_3 r_n_3 2 r_n_1 r_s_1 r_n_4 r_s_4 r_n_5 3 r_n_1 r_s_1 r_n_6 r_s_5 r_n_7 4 r_n_1
column1 column2 column3 colum4 column5
1 r_n_1 r_s_1 r_n_2 r_s_3 r_n_3
2 r_n_1 r_s_1 r_n_4 r_s_4 r_n_5
3 r_n_1 r_s_1 r_n_6 r_s_5 r_n_7
4 r_n_1 r_s_1 r_n_6 r_s_6 r_n_9
5 r_n_10 r_s_7 r_n_11 r_s_8 r_n_12
6 r_n_10 r_s_9 r_n_11 r_s_10 r_n_13
我想在数据框中合并单元格,这样我就可以在excel中编写
所以基本上合并excel中具有相同值的单元格。我想我能
使用熊猫的多重索引,但我不知道怎么做
我获取此数据帧的代码如下
new_list = []
for k1 in remove_empties_from_dict(combined_dict):
curr_dict = remove_empties_from_dict(combined_dict)[k1]
for k2 in curr_dict:
curr_dict_2=curr_dict[k2]
for k3 in curr_dict_2:
curr_dict_3=curr_dict_2[k3]
for k4 in curr_dict_3:
curr_dict_4=curr_dict_3[k4]
new_dict= {'c1': k1, 'c2': k2, 'c3': k3, 'c4': k4,'c5': curr_dict_4}
new_list.append(new_dict)
df = pd.DataFrame(new_list)
我找不到一个直接函数来合并具有相似值的单元格,因此,我编写了一个代码来实现这一点
print(df)
column1 column2 column3 column4 column5
0 r_n_1 r_s_1 r_n_2 r_s_3 r_n_3
1 r_n_1 r_s_1 r_n_4 r_s_4 r_n_5
2 r_n_1 r_s_1 r_n_6 r_s_5 r_n_7
3 r_n_1 r_s_1 r_n_6 r_s_6 r_n_9
4 r_n_10 r_s_7 r_n_11 r_s_8 r_n_12
5 r_n_10 r_s_9 r_n_11 r_s_10 r_n_13
这是我必须与之合作的df。但为了做到这一点,我做了一次迭代,检查哪些值相似,并用-
替换。我之所以没有使用NoneType
是因为表下面的单元格有一个NoneType
值,因此代码的下一部分将继续无限迭代。我所做的是:
for i in df.columns:
for j in range(len(df[i])):
for k in range(j+1,len(df[i])):
if df[i][j]== df[i][k]:
df[i][k]='-'
现在我的df
看起来像:
print(df)
column1 column2 column3 column4 column5
0 r_n_1 r_s_1 r_n_2 r_s_3 r_n_3
1 - - r_n_4 r_s_4 r_n_5
2 - - r_n_6 r_s_5 r_n_7
3 - - - r_s_6 r_n_9
4 r_n_10 r_s_7 r_n_11 r_s_8 r_n_12
5 - r_s_9 - r_s_10 r_n_13
既然数据框中有了所有唯一的值,我将检查df
元素是有效的输入还是-
。而-
的单元格将与其上限值合并。我是这样做的:
from openpyxl.workbook import Workbook
exportPath = r'C:\Users\T01144\Desktop\PythonExport.xlsx'
wb= Workbook()
ws=wb.active
rowInd=1
colInd=1
colList=['-', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I'] # Continue if there are more columns
for i in df.columns:
for j in range(0,len(df[i])):
if(df[i][j]!='-'):
ws.cell(row=rowInd,column=colInd,value=df[i][j])
else:
count=0
for l in range(j+1,len(df[i])):
count+=1
if df[i][l]!='-':
count-=1
break
ws.merge_cells(str(str(colList[colInd]+str(rowInd-1))+":"+str(colList[colInd]+str(rowInd+count))))
rowInd+=1
colInd+=1
rowInd=1
我现在的输出是:
整个代码都可以找到
注意:有些人在创建Excel后可能会出现以下错误:
我们发现“PythonExport.xlsx”中的某些内容存在问题。你想让我们尽力恢复吗?如果您信任此工作簿的来源,请单击“是”
只需忽略此错误并单击“是”。因此,对于您不工作的情况,
df.将索引(['c0'、'c1'、'c2'、'c3'])设置为excel('file.xlsx')
?@jezrael No,它只是按指定格式排列列。它不会合并具有相同值的单元格。非常感谢您的努力。你真的做了很多。我很感激。你能解释一下你用indf=0做什么吗?@NoobProgrammer很抱歉,这是我在编写代码时用来调试代码的一个变量。它不是最终代码的一部分。我已经在编辑中删除了它。它给了我这样一个信息:试图在数据帧的切片副本上设置一个值。请参阅文档中的注意事项:df[I][k]='-',它不会从此点向前移动。