import pandas as pd
#读取 excel 并获取字段
df=pd.read_excel('666.xlsx',dtype=str)
col_list=list(df.columns)
#需要删除的字段名
del_col_list =['c','d']
# 构造备注列,把要删除的列 变为dic
df['beizhu'] =df[del_col_list].to_dict(orient='records')
# 构造不包含del_col_list内元素字段的df表
df=df[[x for x in col_list if x not in del_col_list]+["beizhu"]]
print(df)
#OK了
df.to_excel('777.xlsx',index=False)
以下是老代码,比较繁琐
#%%
import pandas as pd
df=pd.read_excel('工作表.xlsx')
col_list=list(df.columns)
del_col_list =['c','d'] #需要删除的字段名
# 构造备注列
df['beizhu']=''
for column in del_col_list:
df['beizhu']=df['beizhu']+f'''"{column}":'''+'"'+df[column].astype(str)+'",'
df['beizhu']='{'+df['beizhu'].astype(str).apply(lambda x:x.strip(','))+'}'
#把要删除的字段在col_list中删去,并加上'beizhu'字段
for del_col in del_col_list:
col_list.remove(del_col)
col_list.append('beizhu')
print(col_list)
#根据col_list 保留列
df=df[col_list]
#OK了
df.to_excel('666.xlsx',index=False)
本文来自博客园,作者:o0o0o9,转载请注明原文链接:https://www.cnblogs.com/o0o0o9/p/16742703.html