JamesHudson81
JamesHudson81

Reputation: 2273

turn double square brackets to single

How can I remove the double square brackets of a numpy array to single square brackets like a list?

[[0, 3.49, 0, 4.55]]

desired output

[0,3.49,0,4.55]

I have searched through SO looking for numpy array to list , square brackets numpy, not being able to find an answer

to_list() only add commas among the values

Upvotes: 5

Views: 22791

Answers (3)

thistleknot
thistleknot

Reputation: 1158

I had this same problem and referencing [0] did not work (it would simply select the 1st element, in this case [0])

I was trying to setup a way to automate iterator "i" in code from here https://www.datasklr.com/ols-least-squares-regression/interaction-effects-and-polynomials-in-multiple-linear-regression

so I tried

X_inter.iloc[:, np.array(pd.concat([pd.DataFrame(range(0,len(all_data.iloc[:,2:].columns))),pd.DataFrame(pd.Series(i))]).values)]

which would throw an error "Buffer has wrong number of dimensions (expected 1, got 2)"

My np.array would look like this

array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

Found a solution here that worked

https://www.quora.com/How-can-I-drop-brackets-in-a-Python-list-in-order-to-go-from-1-2-3-to-1-2-3

test_list = np.array(pd.concat([pd.DataFrame(range(0,len(all_data.iloc[:,2:].columns))),pd.DataFrame(pd.Series(i))]).values)

flattened = [] 
for sublist in test_list: 
    for val in sublist: 
        flattened.append(val) 

X_inter.iloc[:, flattened]

Upvotes: 0

Phung Duy Phong
Phung Duy Phong

Reputation: 896

Are you sure it was a numpy array?

I think just use

my_list[0] 

to get the first element (in the first element is [0,3.49,0,4.55])

Upvotes: 4

PMonti
PMonti

Reputation: 460

If they are coded as lists, you can just take the [0] element

Upvotes: 13

Related Questions