简体   繁体   中英

Transforming pandas data frame into excel with below format

I have my pandas data frame as line below.

在此处输入图像描述

I need to convert the above dataframe as below in python and save result in Excel sheet with proper indentation.

在此处输入图像描述

Any help will be grateful. Thanks

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")

When you will open csv file use wrap text to see details as were mentioned in snapshot.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM