0

I have data in string format like:

str1 = "[0,-1.5],[-12.5,1.5],[12.5,1.5],[12.5,-1.5],[-12.5,-1.5])"

I want to put this data into an excel file. means 1st value from the array will go in x Col and 2nd value will go in Y col. this will be repeated until the whole string will be added to the x and y columns. I am attempting like, first convert the string into dataframe and then dataframe to an excel file. but it's giving me an error of "Empty DataFrame".

    bad_chars = [';', ':', '(', ')', '[', ']']
s = ""
for i in str1:
    if i not in bad_chars:
        s += i
print(s)

StringData = StringIO(s)


df = pd.read_csv(StringData, sep=",")

# Print the dataframe
print(df)

enter image description here

1
  • 1
    Is str1 correctly specified? Does it have only one round bracket? Commented Nov 23, 2022 at 21:02

1 Answer 1

1

You can use pandas.Series.str.extractall :

out = (
        pd.Series([str1])
            .str.extractall(r"(-?\d+\.?\d*,-?\d+\.?\d*)")
            .reset_index(drop=True)
            [0].str.split(",", expand=True)
            .rename(columns= {0: "X", 1: "Y"})
            .applymap('="{}"'.format)
      )
​

# Output :

print(out)

          X        Y
0      ="0"  ="-1.5"
1  ="-12.5"   ="1.5"
2   ="12.5"   ="1.5"
3   ="12.5"  ="-1.5"
4  ="-12.5"  ="-1.5"

Then, you can use pandas.DataFrame.to_excel to put this dataframe in a spreadsheet:
out.to_excel("path_to_the_file.xlsx", index=False)

Sign up to request clarification or add additional context in comments.

5 Comments

it's extracting the data but there is one issue. I have very large data, like these values [0.55,-2.1375],[0.55,-1.9625]. it should extract X: Y: 0.55, -1.1375, 0.55, -1.9625, but I am getting wrong like this X: Y: 55, -1.1375, 55, -1.9625,
I updated the regex pattern ;)
it should be 0.55 in X col but I am getting 55 instead
Have you checked my updated answer ?
It's an Excel problem if this one get rid of the leading zero, I updated my answer to handle this ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.