简体   繁体   中英

How to use pandas or equivalent python library to parse a csv file

I have a csv file data.csv with below file content(| delimited)

A|B|X|Y|Z
S|T|U|V|W|X

I want to parse this file to print the data in below format(1st two columns constant and third column split by | and generate new row

A|B|X
A|B|Y
A|B|Z
S|T|U
S|T|V
S|T|W
S|T|X

Try with read_csv and melt :

df = pd.read_csv('data.csv', sep='|', header=None).melt([0,1])

Output:

print(df.melt([0,1]))

         0           1  variable         value
0  1338980  2528742011         2  B00HFPOXM4:0
1  1338981  2528742012         2  B00HFPOXCY:0
2  1338980  2528742011         3  B00HFPOX9C:0
3  1338981  2528742012         3  B00HFPOX9W:0
4  1338980  2528742011         4  B00NPZ7WNU:0
5  1338981  2528742012         4  B00HFPOVCG:0
6  1338980  2528742011         5  B00HFPOXCO:0
7  1338981  2528742012         5  B00KGBX5DC:0

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