Home > OS >  How to collect elements of each position in brackets and write them in the csv file in python
How to collect elements of each position in brackets and write them in the csv file in python

Time:11-02

   {1,2,3},{4,5,6},{7,8,9},{10,11,12}...

I have the above set of brackets. All I want to do is, write each column in the csv file with those valuse in brackets.

a   b   c
1   2   3
4   5   6
7   8   9
10  11  12

This is what I want to get in csv. I looked for normal distribution equations and how to switch to dataframe.

df = pd.DataFrame([["asdf(q3de(18)), ( england 2020 )", 2, 3],
                ["aecf(bwe(34))/ ( korea( 2020 ))", 2, 3],
                ["nwvf(bsde(6g)) - (china(2020)", 2, 3]],
                columns = ["brand", "height", "weight"])

for i in range(len(df)):
   df['brand'][i] = re.sub(regex, '', df['brand'][i])
   print(df['brand'][i])

#this prints like this
print(df)
'''
   brand height  weight
0  asdf    2      3
1  aecf    2      3
2  nwvf    2      3

Some of the information I found is the same way as above. But as I intended, I don't have a sense of how to call the order of certain positions in brackets. If it was a list, I could have used [0], [1], etc., but this case is different because I used curly brackets. I don't know how to deal with the position for brackets.

CodePudding user response:

An approach could be like this using ast.literal_eval():

import ast
st = "{1,2,3},{4,5,6},{7,8,9},{10,11,12}"
st = st.replace('{', '[')
st = st.replace('}', ']')
st = list(ast.literal_eval(st))

This results in

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

which you can index and use easily.

Also, here just using ast.literal_eval(st) would return st as a tuple of lists like

([1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12])

which is also iterable and you can avoid casting to list explicitly.

  • Related