1

Using the following function:

def exportExcel(data):
    df = pd.DataFrame(data)
    filepath = 'Output.xlsx'
    df.to_excel(filepath, index=False) 

Output after exporting the np.array to excel columns

    column a       column b     column c
    [[0.00536237] [0.00536237]] [0.01030928]
    [[0.00652899] [0.00652899]] [0.]
    [[0.00579218] [0.00579218]] [0.]

How can I remove all the squared brackets?

I have tried several solutions, but they don´t work:

for col in df:
df[col] = df[col].str.extract(r'\[(.*)\]')

Thank you

2
  • 2
    What do you see for type(df['column a'].iloc[0]) ? It's important to know whether you have strings, a list, an array, or something else. Commented Aug 7, 2018 at 11:33
  • AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas Commented Aug 7, 2018 at 11:42

2 Answers 2

3

If the column is in numpy, you can make use of the function np.squeeze()

df[col]=np.squeeze(df[col].tolist())
Sign up to request clarification or add additional context in comments.

Comments

2

If they are string, you can use replace:

df[col] = df[col].str.replace('[','')
df[col] = df[col].str.replace(']','')

Or if the square brackets you want to remove are only at the start or end of the string, with strip:

df[col] = df[col].str.strip('[')
df[col] = df[col].str.strip(']')

6 Comments

I see this: AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
What type are the columns? see jpp comment
I can´t see the type
they are the square brackets of a numpy array
TypeError: unhashable type: 'numpy.ndarray'
|

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.