将熊猫数据框转换为具有以下格式的excel
Posted
技术标签:
【中文标题】将熊猫数据框转换为具有以下格式的excel【英文标题】:Transforming pandas data frame into excel with below format 【发布时间】:2020-11-04 16:49:40 【问题描述】:我的 pandas 数据框如下所示。
我需要在 python 中将上述数据框转换为如下所示,并将结果保存在具有适当缩进的 Excel 工作表中。
任何帮助将不胜感激。谢谢
【问题讨论】:
【参考方案1】:df = pd.DataFrame("CLIENTID":["A","A","A","I","I"], "Key1":["VI","SA","SU","RA","RA"],
"Key2":["NA","RA","VI","VI","VI"], "Key3":["KA","AZ","KA","NA","SA"],
"Key4":["AV","AV","AZ","AZ","SU"], "Value1":["1-3","2-5","234","78-127","0-28"],
"Value2":["as","ad","adw","ds","sd"],"Value3":["ads","add","addw","dfs","wsd"],
"Value4":["N","Y","N","N","TRUE"], "AVG":[123,321,344,233,432], "AMOUNT":[98,67,45,44,56])
l1 = []
l2 = []
l3 = []
l4 = []
for key,value in df.iterrows():
l1.append(value[0])
temp = value[1]+": "+value[5]+"\n"+value[2]+": "+value[6]+"\n"+value[3]+": "+value[7]+"\n"+value[4]+": "+value[8]
l2.append(temp)
l3.append(value[9])
l4.append(value[10])
updated_df = pd.DataFrame(list(zip(l1,l2,l3,l4)),columns =['CLIENTID', "Key-Value","AVG","AMOUNT"])
updated_df.to_csv("data.csv")
当您打开 csv 文件时,使用自动换行来查看快照中提到的详细信息。
【讨论】:
以上是关于将熊猫数据框转换为具有以下格式的excel的主要内容,如果未能解决你的问题,请参考以下文章