How to convert list to a list of numpy arrays?

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to convert list to a list of numpy arrays?



I have the following list [1 2 3 4 5 6 7 8]. How can I convert this to a list of [[1 2 3] 4 5 [6 7 8]].


[[1 2 3] 4 5 [6 7 8]]



Better yet, I have 1 2 3 4 5 6 7 8 as a row in my dataframe and I'd like to convert my dataframe to instead have 4 columns where the first entry in this row is [1 2 3], the second one is 4, and the third and fourth entries are 5 and [6 7 8]. Of course I'd like to do that for every row in my dataframe too, not just this row.


1 2 3 4 5 6 7 8


[1 2 3]


4


5


[6 7 8]



Anyone know a way to do this?





How is [[1 2 3] 4 5 [6 7 8]] supposed to be a list of NumPy arrays?
– user2357112
yesterday


[[1 2 3] 4 5 [6 7 8]]




1 Answer
1



IIUC


df = pd.DataFrame({k: k for k in range(1,9)}, index=range(5))

1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8
1 1 2 3 4 5 6 7 8
2 1 2 3 4 5 6 7 8
3 1 2 3 4 5 6 7 8
4 1 2 3 4 5 6 7 8

>>> pd.DataFrame({'0': df[[1,2,3]].agg(np.array, 1),
'1': df[4],
'2': df[5],
'3': df[[6,7,8]].agg(np.array, 1)})

0 1 2 3
0 [1, 2, 3] 4 5 [6, 7, 8]
1 [1, 2, 3] 4 5 [6, 7, 8]
2 [1, 2, 3] 4 5 [6, 7, 8]
3 [1, 2, 3] 4 5 [6, 7, 8]
4 [1, 2, 3] 4 5 [6, 7, 8]





That gives me an error....says "int object not iterable".
– Glassjawed
yesterday





@Glassjawed then post your dataframe for us to understand... do print(df.head(5).to_dict()) and post to question
– RafaelC
yesterday


print(df.head(5).to_dict())





I'm using the same dataframe as you.
– Glassjawed
yesterday





I have edited the question, maybe you got the code from before? Try again with the code you're seeing now. If still error, what version of pandas are you using? make sure there is the .agg at the end of 1st and last column
– RafaelC
yesterday




.agg





nope still no luck.
– Glassjawed
yesterday






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

EA15otIbNy,r2BPyYc BO6rDgrV10fR6a1k,jvRDrhPtY2U30OC7 v2l bk1Vok0aiymDk7pGWXM1ZmzTiT39m,zMyInG7cl,39a1EBV
rh IZ4FR arag C0sBK74Ekt564Q4vaYF2DiHyRDyNZp,UmoKYoj2m8xpNIQ64y hxHBZeAC

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

415 Unsupported Media Type while sending json file over REST Template