Search code examples
pythoncsvdata-science

Remove numbers in tuples and enter them in new rows in csv


so I have an ugly CSV file with one column and only 2 rows, but it has many tuples in it, that looks like:

Column A
(1, 2, 3)(4, 5, 6)(7, 8, 9)
(3, 2, 1)(5, 3, 6)(9, 8, 7)

and I want to have it looks like

Column A Column B Column C
1 2 3
4 5 6
7 8 9
3 2 1
5 3 6
9 8 7

any suggestions?


Solution

  • Since you have a tag, why not use ?

    #pip install pandas
    import pandas as pd
    
    df = (pd.read_csv("input.csv", sep="|").squeeze()
               .str.strip("()").str.split("\)\(", expand=True)
               .melt(ignore_index=False)["value"].str.split(",\s*", expand=True)
               .sort_index().set_axis(["Column A", "Column B", "Column C"], axis=1)
          )
    

    Output :

    print(df)
    
         Column A Column B Column C
    0        1        2        3
    0        4        5        6
    0        7        8        9
    1        3        2        1
    1        5        3        6
    1        9        8        7