简体   繁体   中英

How to append header to the data in csv file created by python dataframe

I have data available in a dataframe

EMP_ID,EMP_NAME,AGE
1,X,71
2,Y,70
3,Z,78

How can i convert above data into below format

EMP_ID:1|EMP_NAME:X|AGE:71
EMP_ID:2|EMP_NAME:Y|AGE:70
EMP_ID:3|EMP_NAME:Z|AGE:78
#

Viceversa Scenario:

Can we convert the below data

EMP_ID,EMP_NAME,AGE
1,X,71
2,Y,70
3,Z,78

again back to

 EMP_ID,EMP_NAME,AGE 1,X,71 2,Y,70 3,Z,78 

df.columns = df.columns +'|'+ df.iloc [0 ,:]

This is probably not the most efficient option, but you could just loop through the dataframes columns and then apply a basic function to each.

Note: all your columns must be a string now.

for col in df.columns:
    df[col] = df[col].apply(lambda x: col +':' + str(x))

And to reverse it, use a similar logic using string slicing:

for col in df.columns: 
    df[col] = df[col].apply(lambda x: x[len(col)+1:])

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