簡體   English   中英

將pandas系列中的嵌套列表解壓縮到新的DataFrame中

[英]Unpack nested lists from a pandas series into a new DataFrame

我有一個數據幀df,它的列[“shares”]似乎是列表中的列表

0     [[10], [9], [9]]
1     [[3], [3], [2]]
2     [[17], [17], [18]]

如何將此列拆分為3列:

col1 col2 col3
10   9     9
3    3     2
17   17    18

我試過df["shares"].apply(literal_eval)但它給了我錯誤的格式錯誤的節點或字符串:

展平列表列表,然后使用DataFrame構造函數

import itertools
pd.DataFrame(list(map(lambda x : list(itertools.chain(*x)),df.shares.tolist())))
    0   1   2
0  10   9   9
1   3   3   2
2  17  17  18

您需要解壓縮列表並重新構建框架。

cols = ['col1', 'col2', 'col3']
pd.DataFrame(([c[0] for c in r] for r in df.shares.tolist()), columns=cols)

   col1  col2  col3
0    10     9     9
1     3     3     2
2    17    17    18

要概括為具有3個以上子列表的列表,您可以使用

pd.DataFrame(
    [c[0] for c in r] for r in df.shares.tolist()
).rename(columns=lambda x: f'col{x+1}')

   col1  col2  col3
0    10     9     9
1     3     3     2
2    17    17    18

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM