I need to convert series which has array within array to a list. This is the series:
0
0 [[136.26198653744652]]
1 [[595.1701354429704]]
2 [[106.31607570796812]]
3 [[579.6333400908089]]
4 [[402.1731384585597]]
5 [[380.381375557186]]
type(b1)
Out[130]: pandas.core.series.Series
b1[1]
Out[131]: array([[595.1701354429704]], dtype=object)
I have tried tolist(),.values or to_numpy() etc. Nothing worked except the following
b1.explode().explode().tolist()
This is what I got. [136.26198653744652, 595.1701354429704, 106.31607570796812, 579.6333400908089, 402.1731384585597, 380.381375557186]
To my understanding here explode does unboxing/unlisting like thing. I'm looking for some better solution here which helps to change the type of every element of a series and produce the result of b1.explode().explode().tolist().
Use 2 times flatten lists in Series
:
L = [z for x in b1 for y in x for z in y]
print (L)
[136.26198653744652, 595.1701354429704, 106.31607570796812,
579.6333400908089, 402.1731384585597, 380.381375557186]
an alternative, using chain from itertools
data ={ 0 : [[[136.26198653744652]], [[595.1701354429704]], [[106.31607570796812]], [[579.6333400908089]], [[402.1731384585597]], [[380.381375557186]]]}
df = pd.DataFrame(data)
from itertools import chain
combine = chain.from_iterable
list(combine(combine(df[0])))
[136.26198653744652,
595.1701354429704,
106.31607570796812,
579.6333400908089,
402.1731384585597,
380.381375557186]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.